简体   繁体   English

独特的约束技巧-实体框架

[英]Unique Constraint Hack - Entity Framework

Since there is not any way to add unique constraint to entities in current latest EF version I came up with an idea. 由于在当前最新的EF版本中没有任何方法可以向实体添加唯一约束,因此我想到了一个主意。 ( I know constraints can be added by embedding SQL ) (我知道可以通过嵌入SQL添加约束)

I added a method to my Repository class : 我在我的Repository类中添加了一个方法:

private IDbSet<T> Entities;

public virtual bool Contains(Func<T, bool> predicate)
{
        return Entities.Any(t => predicate(t));
}

I think this will replace my current duplicate prevention logic: 我认为这将取代我目前的重复预防逻辑:

bool already exists = (from t in someSet.Entities 
                       where t.UniqueColumn == entity.UniqueColumn select t).
                       FirstOrDefault() != null;

if(alreadyExists)
throw new Exception("Entity already exists in DB.");

Is this a good idea, what is the best way to prevent duplicate insertions / updates to database? 这是一个好主意,什么是防止重复插入/更新数据库的最佳方法?

EDIT : I edited the Contains method to use a predicate. 编辑 :我编辑了包含方法以使用谓词。 Now I can write a code like this: 现在,我可以编写如下代码:

if(repository.Contains(t=> t.Email == "someemail@email.com")
     throw new Exception("Email already exists.");

If this is going to be a rare situation, then there's nothing wrong with placing a unique constraint on the database and then catching the exception that gets generated when you try to insert an existing record. 如果这将是一种罕见的情况,那么在数据库上放置一个唯一约束,然后捕获尝试插入现有记录时生成的异常,这没有什么错。

If this is likely to happen a lot, then I would still place the constraint on the database, but do the check as you are. 如果很可能会发生这种情况,那么我仍将约束放在数据库上,但是请按原样进行检查。

FWIW, you should make your method take an Expression<Func<T, bool>> so that the query does not get converted to an Enumerable. FWIW,您应该使您的方法采用Expression<Func<T, bool>>以便查询不会转换为Enumerable。

Well, this won't work because you need to declare what you want to enforce uniqueness on. 嗯,这行不通,因为您需要声明要在其上实施唯一性的内容。 On the primary key? 在主键上? On some other column like "UserName"? 在其他列上,例如“ UserName”吗? On the User.EMail column, but only if it is not null (so you can have multiple users with a null EMail at the same time)? 在User.EMail列上,但仅当它不为null时(这样您才能同时使多个用户具有一个null的EMail)?

I prefer such things to be explicit. 我希望这些事情是明确的。 So I'd actually prefer the logic that you had previously. 所以我实际上更喜欢您以前的逻辑。

在数据库中实施唯一性的最佳方法是使用唯一性约束

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM