我需要 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。在这种情况下,我希望使用新数据更新数据库中的数据。我怎样才能做到这一点?
数据库中的数据
表地址
地址ID 位置
1 约翰广场
2 玛丽广场
3 吉米广场
我更新的用户在 Addresses 集合 1 中具有 AddressId:2,Location=GeorgePlace。但是对于 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.