简体   繁体   English

锁定实体框架

[英]Locking in Entity Framework

I use Entity Framework with C#.我将实体框架与 C# 一起使用。

Because actual version has nothing like unique constraint for non-key attributes, I would like (perhaps using TRANSACTIONS) atomically test if some attribute NAME is in some table (entity) and if not, then I would add the new entity and commit.因为实际版本对非键属性没有唯一约束,所以我想(可能使用 TRANSACTIONS)原子地测试某个属性 NAME 是否在某个表(实体)中,如果不是,那么我将添加新实体并提交。

How can this be done?如何才能做到这一点? Or is there a better solution?还是有更好的解决方案?

One way to do it, is to define the constraint on the DB.一种方法是在数据库上定义约束。

Since Entity Framework doesn't know about constraints at the DB level, you should then script the constraint (ie, create a.SQL file) so that you can add it to any new instances of your DB.由于实体框架不知道数据库级别的约束,因此您应该编写约束脚本(即,创建一个.SQL 文件),以便您可以将其添加到数据库的任何新实例中。

Another way to do it is to implement a standard Repository per entity type (such as CustomerRepository) and then to do the check in that repository's Create method.另一种方法是为每个实体类型(例如 CustomerRepository)实现一个标准存储库,然后在该存储库的 Create 方法中进行检查。 This, by itself, does not guarantee unicity since two users may at the same time create an entity with the same name, and the check won't catch it until you try to commit (ie, SaveChanges), but that is also the case when you define the unicity constraint on the DB...这本身并不能保证唯一性,因为两个用户可能同时创建一个具有相同名称的实体,并且在您尝试提交(即 SaveChanges)之前检查不会捕获它,但情况也是如此当您在数据库上定义唯一性约束时...

You have to create unique index for that column in database.您必须在数据库中为该列创建唯一索引。 Transaction will not help because two different instance of application or context will not work against programming level locking.事务将无济于事,因为应用程序或上下文的两个不同实例不会对编程级别锁定起作用。

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

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