实体框架:避免多个省循环引用多个、实体、框架

2023-09-04 06:22:04 作者:果冻乖甜心

我号召我的EF ObjectContext的SaveChanges的时候得到这个异​​常

I'm getting this exception when calling SaveChanges on my EF ObjectContext:

Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints

我认为这个问题是因为我有一个循环依赖于我的数据库模型。

I think the problem is because I have a circular dependency on my DB model.

表用户

标识 ProfilePictureId

表图片

标识 用户ID

我创建一个新用户,并设置图像

I'm creating a new user and setting the picture

var user = _db.Users.CreateObject();
var picture = _db.Pictures.CreateObject();

picture.User = user;
user.ProfilePicture = picture;

_db.SaveChanges();

不过,抛出异常。

But that throws the exception.

如果我加入的SaveChanges()后,我设置图像的用户只是正常的额外调用,我只是想避免双重一趟到数据库。

If I add an extra call to SaveChanges() after I set the picture's User It works just fine, I just want to avoid that double trip to the DB.

如何实现这一目标的任何想法?

Any ideas of how to achieve this?

谢谢!

推荐答案

有没有办法避免调用的SaveChanges 与数据库设计的两倍。你不能将用户与依赖性的图片是未插入(FK会抛出异常),并在同一时间,你不能插入图片与相关用户是未插入(再次FK会抛出异常)。这不是EF的特点,那就是数据库本身。

There is no way to avoid calling SaveChanges twice with your database design. You can't insert user with dependency to picture which is not inserted yet (FK will throw exception) and in the same time you can't insert picture with dependency to user which is not inserted yet (again FK will throw exception). That is not feature of EF that is feature of DB itself.

您也不必避免多个的SaveChanges 要求,因为多个往返。 EF没有命令批处理所以每个插入,更新或删除有自己的往返到数据库反正。

You also don't need to avoid multiple SaveChanges calls because of multiple roundtrips. EF doesn't have command batching so each insert, update or delete has its own roundtrip to database anyway.

如果你想调用的SaveChanges单必须更改数据库,如下所示:

If you want to call single SaveChanges you must change your database as follows:

表用户

ID(PK,IDENTITY)

表图片

ID(PK,FK到Users.Id,没有身份)

这是本机的一比一的关系,其中用户的本金和图片依赖。

This is native one-to-one relation where User is principal and Picture is dependent.