I want to create a generic methods to handle the unique fields in table.
for example I have 2 unique field, and I want to when I call _entities.Add()
automatically checks the 2 unique fields that there is no records in the database with that record. I have this entity
[Index(nameof(Product.ProductNumber), IsUnique = true)]
[Index(nameof(Product.Url), IsUnique = true)]
public class Product
{
public int Id { get; set; }
[Required]
[MaxLength(50)]
public string Title { get; set; }
public int ProductNumber { get; set; }
[Required]
[MaxLength(50)]
public string Url { get; set; }
}
Now this is my generic service
public class GenericService<TEntity> : IGenericService<TEntity> where TEntity : class
{
private readonly DbSet<TEntity> _entities;
public GenericService(ApplicationDbContext dbContext)
{
_entities = dbContext.Set<TEntity>();
}
public bool Add(TEntity entity)
{
List<string> uniqueFieldsOfEntity = entity.GetType()
.GetCustomAttributes<IndexAttribute>()
.Where(x => x.IsUnique)
.Select(x => x.PropertyNames.FirstOrDefault())
.Where(x => x != null)
.ToList();
foreach (string uniqueField in uniqueFieldsOfEntity)
{
// HERE how can I work with Any with just a string
//var hasAlready = _entities.Any(x => x.uniqueFiled == entity.uniqueFiled);
if (hasAlready)
return false;
}
_entities.Add(entity);
}
}
Aucun commentaire:
Enregistrer un commentaire