Похожие чаты

Yes, abstracting the logic to be reusable across multiple entities

based on dynamic properties can be achieved using a combination of generics, reflection, and expressions. The idea would be to create a generic validation service that can validate any entity based on specified unique properties.

Here's a high-level approach:

### 1. Define a Generic Repository Method

First, you'd need a way to find an entity by a given property in your repositories. A generic method could look like:

public async Task<TEntity> FindByPropertyAsync<TEntity, TValue>(Expression<Func<TEntity, bool>> predicate) where TEntity : class;

### 2. Create a Generic Validation Service

This service will use reflection to validate entities based on provided properties.

public interface IUniquePropertyValidationService
{
Task<(bool IsValid, string ErrorMessage)> ValidateUniquePropertyAsync<TEntity, TValue>(
TEntity entity,
Expression<Func<TEntity, TValue>> propertySelector,
TValue value,
int? entityId = null) where TEntity : class, new();
}

public class UniquePropertyValidationService : IUniquePropertyValidationService
{
private readonly IUnitOfWork _unitOfWork;

public UniquePropertyValidationService(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}

public async Task<(bool IsValid, string ErrorMessage)> ValidateUniquePropertyAsync<TEntity, TValue>(
TEntity entity,
Expression<Func<TEntity, TValue>> propertySelector,
TValue value,
int? entityId = null) where TEntity : class, new()
{
// Convert the property selector to a predicate.
var parameter = Expression.Parameter(typeof(TEntity), "x");
var body = Expression.Equal(propertySelector.Body, Expression.Constant(value, typeof(TValue)));
var lambda = Expression.Lambda<Func<TEntity, bool>>(body, parameter);

var existingEntity = await _unitOfWork.YourGenericRepository.FindByPropertyAsync(lambda);

if (existingEntity != null)
{
// If we have an entityId, we're in update mode, so we check if the found entity's ID matches the updating entity's ID.
var existingEntityId = (int)typeof(TEntity).GetProperty("Id").GetValue(existingEntity);
if (!entityId.HasValue || existingEntityId != entityId.Value)
{
var propertyName = ((MemberExpression)propertySelector.Body).Member.Name;
return (false, $"{typeof(TEntity).Name} with the same {propertyName} already exists.");
}
}

return (true, string.Empty);
}
}

### 3. Use the Service

For instance, for the currency entity:

var validationOutcome = await _uniquePropertyValidationService.ValidateUniquePropertyAsync<Currency, string>(
currencyToUpdate,
x => x.CurrencyCode,
request.CurrencyCode,
request.CurrencyId);

### Caveats:

- This approach assumes all entities have an Id property of type int. Adjustments might be necessary for different setups.
- Reflection can introduce overhead, so while this generic solution is elegant, there might be performance concerns when dealing with large volumes of data or frequent operations.
- The abstraction assumes uniqueness validation is based on a single property. If there are scenarios where uniqueness is based on combinations of properties, further adjustments would be needed.
- This is a more complex solution than having dedicated validation for each entity. Ensure the complexity aligns with your project's needs.

4 ответов

24 просмотра
Leoul-G Автор вопроса

Hey Guys what Do you think of this generic uniqueness validator, it it a good idea ?

how to insert c# code on the message like this ?

Leoul-G Автор вопроса
Houdaifa Bouamine
screenshot how to insert c# code on the message like this ?

surround the code with 3 backticks and right after(or below) the opening backticks write csharp and on the next lines the code

Похожие вопросы

Обсуждают сегодня

А кто-то пробовал, уезжая из Эстонии получить э-рез и продолжить вести предпринимательскую деятельность внутри Эстонии, используя свой OÜ?
Lalalashechki Lalala
57
@MrMiscipitlick А можешь макрос написать, который будет вычислять смещение относительно переданных меток? Просто .label1-.label2, и вернуть значение.
КТ315
35
я не магистр хаскеля, но разве не может лейзи тип конвертнуться в не-лейзи запросив вычисление содержимого прям при инициализации?
deadgnom32 λ madao
100
А еще в перле можно уже @arr1 + @arr2?
Sergei Zhmylove
53
Does anyone here have a connection Mullvad? it would be nice to know what it would take to have them accept BCH 0-conf.
tl121x
16
Подобного рода ;Следующие три строки это директивы ассемблера, ;которые можно не задавать, т.к.работаем в Visual Studio. ;Символ ";" - это начало однострочного комментария ...
Егор Анелькин
3
@samkazemian - couple questions: Update on frxBTC? - This would do well with the current influx of institutional investment entering the space Update on future veFXS streams...
Costi
9
Can an XMR transaction be tracked from its sender to its receiver by performing blockchain analysis, no matter how many addresses are used?
Trkz342
15
I arrived here after a Chico Crypto show highlighted the project & the Team - the fact that the Team had a long history of successfully working with household names gave me e...
Banter is Bullish
5
Привет всем. появился вопрос. Разрабатываю сайт, в данный момент он запущен. Хостинг beget. Добавляю на сайт яндекс метрику с помощью полей client-settings (взято отсюда http...
Andrew
2
Карта сайта