实体框架不会保存关系

时间:2022-01-22 10:05:26

I have the following situation:

我有以下情况:

role.Permissions.Add(permission);
objectContext.SaveChanges();

When I now take a look in the relations table Roles_Permissions the newly added permission to the role is not present. It only saves the new relation when I dispose the object context. Am I doing something wrong or does a call to SaveChanges doesn't save changes on relationship sets?

现在我在关系表Roles_Permissions中查看新添加的角色权限不存在。它只在我处理对象上下文时保存新关系。我做错了什么或者调用SaveChanges是不是保存关系集的更改?

4 个解决方案

#1


1  

Check the ObjectStateManager - before calling SaveChanges, have a look on the object state manager to get all changes that have a state of Added - it should return just the one item which is that permission object. If it's not in there, something else is wrong. Calling SaveChanges should persist your changes then and there.

检查ObjectStateManager - 在调用SaveChanges之前,查看对象状态管理器以获取状态为Added的所有更改 - 它应该只返回该权限对象的一个​​项目。如果它不在那里,那么别的东西就错了。调用SaveChanges应该在那里和那里保持你的更改。

#2


0  

It sounds like you are using a transaction.

这听起来像是在使用交易。

The changes made are not visible outside the transaction scope untill the transaction is committed.

在提交事务之前,所做的更改在事务范围之外是不可见的。

And the transaction scope is not being committed until the object context is disposed.

并且在处理对象上下文之前不会提交事务范围。

#3


0  

Just check whether they are in the same objectContext.

只需检查它们是否在同一个objectContext中。

#4


0  

You can ensure that your permission entity is known to your object context by executing the following line of code:

您可以通过执行以下代码行来确保您的权限实体为您的对象上下文所知:

objectContext.AddObject("Permissions", permission);

#1


1  

Check the ObjectStateManager - before calling SaveChanges, have a look on the object state manager to get all changes that have a state of Added - it should return just the one item which is that permission object. If it's not in there, something else is wrong. Calling SaveChanges should persist your changes then and there.

检查ObjectStateManager - 在调用SaveChanges之前,查看对象状态管理器以获取状态为Added的所有更改 - 它应该只返回该权限对象的一个​​项目。如果它不在那里,那么别的东西就错了。调用SaveChanges应该在那里和那里保持你的更改。

#2


0  

It sounds like you are using a transaction.

这听起来像是在使用交易。

The changes made are not visible outside the transaction scope untill the transaction is committed.

在提交事务之前,所做的更改在事务范围之外是不可见的。

And the transaction scope is not being committed until the object context is disposed.

并且在处理对象上下文之前不会提交事务范围。

#3


0  

Just check whether they are in the same objectContext.

只需检查它们是否在同一个objectContext中。

#4


0  

You can ensure that your permission entity is known to your object context by executing the following line of code:

您可以通过执行以下代码行来确保您的权限实体为您的对象上下文所知:

objectContext.AddObject("Permissions", permission);