![]() ![]() This is Part 2 of the series "Best ways of implementing Uniqueness or Unique Key attribute on a model property in ASP. ![]() ![]() This update eradicated this problem and made the code more simple to understand. It did not allow to pass the original value of unique field while updating the others. You can even use this across multiple properties to form a Unique Key across multiple columns in your table.Like Part 1, before this update, unfortunately there was a serious problem which went unnoticed that the method used to work fine in case of creating new entity only but did not work properly in case of Edit/Updating any existing entity. Usage in your Entity.cs class: public class Company Throw new ArgumentNullException(nameof(property.Name)) Throw new ArgumentNullException(nameof(property)) Throw new ArgumentNullException(nameof(entityType.ClrType)) Throw new ArgumentNullException(nameof(entityType)) #endregion Convert UniqueKeyAttribute on Entities to UniqueKey in DBĪlso in your DbContext.cs class, add this private method: private static IEnumerable GetUniqueKeyAttributes(IMutableEntityType entityType, IMutableProperty property) If ((uk != null) & (uk.GroupId = uniqueKey.GroupId))ĮntityType.AddIndex(mutableProperties).IsUnique = true Var uks = GetUniqueKeyAttributes(entityType, x) If (String.IsNullOrWhiteSpace(uniqueKey.GroupId))ĮntityType.AddIndex(property).IsUnique = true Var uniqueKeys = GetUniqueKeyAttributes(entityType, property) įoreach (var uniqueKey in uniqueKeys.Where(x => x.Order = 0)) If ((properties != null) & (properties.Any())) Var properties = entityType.GetProperties() #region Convert UniqueKeyAttribute on Entities to UniqueKey in DB In your DbContext.cs file, inside OnModelCreating(modelBuilder) method, add this: // Iterate through all EF Entity typesįoreach (var entityType in ()) we simply return success as no actual data validation is needed because this class implements a "marker attribute" for "create a unique index" ![]() Protected override ValidationResult IsValid(object value, ValidationContext validationContext) Public UniqueKeyAttribute(string groupId = null, int order = 0) / Optional, used to order the entity properties that are part of a combined Unique Key / Optional, used to group multiple entity properties together into a combined Unique Key Public class UniqueKeyAttribute : ValidationAttribute / Used on an EntityFramework Entity class to mark a property to be used as a Unique Key I've written an Attribute class that can allow you to decorate your EF Core Entity class properties to cause a Unique Key to be generated (without the Fluent API).
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |