CTP5更新级联
我需要 CTP5 的添加或更新模式。 假设模型:
public class User
{
public int UserId { get; set; }
public ICollection<Address> Addresses { get; set; }
}
public class Address
{
public int AddressID { get; set; }
public string Location { get; set; }
}
如果我添加一个新用户,相应的地址表也会被填充。 但如果用户已经在数据库中,我将收到 DbUpdateException。在本例中,我希望用新数据更新数据库中的数据。我该怎么做?
数据库中的数据
表地址
AddressID Location
1 JohnPlace
2 MaryPlace
3 JimmyPlace
我更新的用户在Addresses 集合中具有AddressId:2、Location=GeorgePlace 的1 项。 但是对于ID=2,在Db中已经有一条location=MarryPlace的记录。我希望 GeorgePlace 覆盖 MarryPlace。
我不能拥有未分配给用户的地址,
我创建了一个用户,例如:
var user=new User();
user.Id=GetUserIDfromService();
foreach(var address in GetAddressesFromService(user.Id)){
user.Addresses.Add(address);
}
context.Users.Add(user);
context.SaveChanges();//this may throw an exception, because there is already a user with this id.
I need an Add or Update pattern for CTP5.
Assuming the model:
public class User
{
public int UserId { get; set; }
public ICollection<Address> Addresses { get; set; }
}
public class Address
{
public int AddressID { get; set; }
public string Location { get; set; }
}
If I add a new User, The coresponding Address table is also populated.
But if the user is already in DB, I will get an DbUpdateException. In this case I want the data in the database to be updated with the new data. How can I do this?
data in database
Table Address
AddressID Location
1 JohnPlace
2 MaryPlace
3 JimmyPlace
The User I update has in the Addresses collection 1 item with AddressId:2, Location=GeorgePlace.
But for ID=2, in the Db there is already a record with location=MarryPlace. I want GeorgePlace to overwrite MarryPlace.
I cannot have an address that is not assigned to a user
I create a user like:
var user=new User();
user.Id=GetUserIDfromService();
foreach(var address in GetAddressesFromService(user.Id)){
user.Addresses.Add(address);
}
context.Users.Add(user);
context.SaveChanges();//this may throw an exception, because there is already a user with this id.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想更新现有用户,请不要插入它(不要调用
Add()
)首先通过 Id 加载用户,然后修改其属性并在上下文中调用
SaveChanges()
。If you want to update an existing user do not insert it (do not call
Add()
)Load the user by Id first than modify it's properties and call
SaveChanges()
on the context.您当前的问题是您准备新的 User 对象并填充其地址,但地址不是通过相同的上下文从数据库加载的,因此上下文不知道它们。当您调用 Add 方法时,它将获取对象图中的所有对象并将它们标记为新对象(要插入)。避免这种情况的唯一方法是在将地址添加到用户实例之前手动说明哪个地址是新的,哪个只是修改或从上下文加载地址。
标记地址的代码如下所示:
Your current problem is that you prepare new User object and fills its addresses but addresses are not loaded from DB via same context so context don't know them. When you call Add method it will take all objects in object graph and marks them as new (to be inserted). The only way to avoid this is manually say which Address is new and which is only modification or load addresses from context before you add them to User instance.
The code for marking addresses can look like: