Options for Unique field in Entity Framework - navigation property to dbSet?

一曲冷凌霜 提交于 2019-11-30 16:12:55

问题


After much research it seems Entity Framework 4.4 doesn't support Unique constraints. Yes it can & should be done at the database, but I'd much prefer it happen in model validation so the warning to user is prettier.

It would be ideal for programmers to be able to decorate the property with a [Unique] attribute and it should be possible somehow, eg.:

public class UserGroup
{

    public int UserGroupID { get; set; }

    [Required]
    [Unique]
    public string Name { get; set; }

    [Required]
    public string Description { get; set; }

}

Options I'm considering:

1) Have the repository do some extra work at SaveChanges(), scan for [Unique] attributes on modified entities and hit the database to check uniqueness. Downside: this validation only happens when we call SaveChanges(), ideally it can happen earlier (eg. when the UI control validates).

2) Give the UserGroup model a lazy-loaded navigation property to AllUserGroups:

public virtual ICollection<UserGroup> AllUserGroups { get; set; }

Then program UniqueAttribute{} to scan this property and check the values etc.

QUESTION: how can I configure Entity Framework (code first) to load all records into this "navigation property"? It only seems to want a navigation property with foreign keys etc while I just want them all.

3) Manually code this validation in the UI - terrible & absolute last resort.

QUESTION: are there any better options for enforcing a Unique Constraint via validation at the model level?

Regards, -Brendan


回答1:


I found this, seems to be the one you're looking for:

UniqueAttribute that validates a unique field against its fellow rows in the database (inherits DataAnnotations.ValidationAttribute)



来源:https://stackoverflow.com/questions/14368937/options-for-unique-field-in-entity-framework-navigation-property-to-dbset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!