尝试了解为什么父实体状态更改时子实体状态不会更改



这是我的模型的样子:

Branch属于OrganisationOrganisation属于User

[Table("branch")]
public class Branch
{
public long BranchId { get; set; }
public string BranchName { get; set; }
public long OrganisationId { get; set; }
[ForeignKey("OrganisationId")]
public Organisation Organisation { get; set; }
}
[Table("organisation")]
public class Organisation
{
public long OrganisationId { get; set; }
public string OrganisationName { get; set; }
public long UserId { get; set; }
[ForeignKey("UserId")]
public UserProfile UserProfile { get; set; }
}
[Table("userprofileview")] // <-- UserProfile is representing a view 
public class UserProfile
{
public long UserId { get; set; }
public string Name { get; set; }
}

UserProfile实体表示视图且不可插入(因为它具有左联接(。

我想向现有Organisation(属于现有User(添加新Branch,以下代码给了我一个错误:

public void AddOrUpdateBranchAsAdminUser(Branch branch)
{
if (branch.BranchId > 0)
{
// code to update branch
}
else
{
_context.Branch.Add(branch);
_context.Entry(branch.Organisation).State = EntityState.Unchanged; // <-- Don't update Organisation 
/*
* uncommenting this line will fix the problem
* _context.Entry(branch.Organisation.UserProfile).State = EntityState.Unchanged;  
*/
_context.SaveChanges();
}
}

这是我得到的错误:

插入

的目标表用户配置文件视图不可插入到

如果我取消注释设置UserProfile状态的行,那么它可以正常工作......有人能够解释这种行为吗?我本以为更改Organisation状态(父实体(也应该更改UserProfile的状态。

这是由于实体框架缓存。

您收到的消息

插入

的目标表用户配置文件视图不可插入到

你得到这个是因为,正如你所说,

用户配置文件实体表示视图,并且不可插入(因为它具有左联接(。

到目前为止,这似乎是有道理的...

删除该行后

_context.Entry(branch.Organisation.UserProfile).State = EntityState.Unchanged;

您将缓存的记录标记为未更改。这意味着当您保存更改((时,实体框架不会尝试将该记录的任何更新推送到数据库。我无法回答用户配置文件如何被"触摸",但您有该属性

[ForeignKey("UserId")]

关于组织。我有一种感觉,因为您正在更改 Organization 对象,实体框架正在尝试"接触"所有子对象。似乎这以某种方式在用户配置文件上生成"插入"。解决方法是将对象设置为"未更改",以便实体框架永远不会尝试将任何修改推送到此表。

编辑:如果 1(生成一个新分支。2( 将组织关联到不在 EF 缓存中的分支。3( 关联的组织具有不在 EF 缓存中的用户配置文件。我认为如果您在这种情况下生成了一个分支,EF 将自动尝试序列化您的相关对象并将它们插入数据库。

如果您更改了类似于

[Table("branch")]
public class Branch
{
public long BranchId { get; set; }
public string BranchName { get; set; }
public long OrganisationId { get; set; }
}
public class BranchComposite
{
public Branch Branch { get; set; }
[ForeignKey("OrganisationId")]
public Organisation Organisation { get; set; }
}

最新更新