我在将实体彼此更改为一个实体时遇到问题:
这是我的测试课程:
public class MyUser
{
public Guid Id { get; set; }
public string Name { get; set; }
public virtual MyAddress MyAddress { get; set; }
}
public class MyAddress
{
public Guid Id { get; set; }
public string AddressLine { get; set; }
public virtual MyUser MyUser { get; set; }
}
这是我的映射:
modelBuilder.Entity<MyAddress>().HasOptional(x => x.MyUser).WithRequired(x => x.MyAddress);
在DB中我有
MyUser ID = "abc", Name = "Test"
MyAddress ID = "abc", AddressLine = "TestAddress"
MyAddress ID = "dfg", AddressLine = "TestAddress2"
否,我要从具有相同ID的MyUser的MyAddress中删除,并向具有其他ID的MyAddress添加到MyUser
// myUser.Id = "abc" myUser.MyAddress.Id = "abc"
// myOldAddress.Id = "abc" myOldAddress.MyUser.Id = "abc"
// myNewAddress.Id = "dfg" myNewAddress.MyUser = null
var myUser = repoUser.GetById("abc")
var myOldAddress = repoAddress.GetById("abc");
myOldAddress.MyUser = null;
var myNewAddress = repoAddress.GetById("dfg");
myUser.MyAddress = myNewAddress;
myNewAddress.MyUser = myUser;
//on save I have this exception and what result i want to have
// myUser.Id = "abc" myUser.MyAddress.Id = "abc"
// myOldAddress.Id = "hjk" myOldAddress.MyUser = null
// myNewAddress.Id = "abc" myNewAddress.MyUser.Id = "abc"
// something like this (substitute)
Exception:
Additional information: A referential integrity constraint violation occurred:
A primary key property that is a part of referential integrity constraint cannot be
changed when the dependent object is Unchanged unless it is being set to the
association's principal object. The principal object must be tracked and not
marked for deletion.
{"A referential integrity constraint violation occurred: A primary key property
that is a part of referential integrity constraint cannot be changed when the
dependent object is Unchanged unless it is being set to the association's
principal object. The principal object must be tracked and not marked for deletion."}
为什么EF不会自动将ID更改为与UserId相同?用户必须具有地址1:1,但地址具有可选的用户1:0
首先,我对用户和地址之间的关系是一对一的设计不满意,既不允许没有用户的地址,也不允许没有地址的用户。因为通常一个普通用户可以有很多地址
但是,根据我们在评论部分的讨论,我得到了以下内容:
数据库中的“地址”表有两列:ID
不允许为null和AddressLine
因此,当您调用myOldAddress.MyUser = null;
代码时,您只需将EF设置Address.Id
为null
违反数据库约束的数据库中的EF
我不建议使用的一种解决方案是Address.Id
允许null
但是我建议将设计更改为以下之一:
因此,您的地址表将如下所示:
ID (not null)
AddressLine
UserId (Nullable) forieng key in User Table
这样,您就可以设置MyAddress.MyUser
到null
在你的代码,安全
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句