[英]Entity framework: adding new objects results in duplicates
我正在开发一个三层WinForms应用程序。 但是,当我尝试向数据库中添加新对象时,某些对象会重复。
类别:
class Customer
{
public int Id { get; set; }
public int CustomerName { get; set; }
public virtual IList<CustomerAccount> CustomerAccount { get; set; }
}
class CustomerAccount
{
public int Id { get; set; }
public int CustomerId { get; set; }
public int AccountId { get; set; }
public virtual Customer Customer { get; set; }
public virtual Account Account { get; set; }
}
class Account
{
public int Id { get; set; }
public int AccountName { get; set; }
}
这是我用来将Customer对象添加到数据库中的代码:
DataContext.CustomerSet.Add(customer);
DataContext.SaveChanges();
添加到客户的帐户是现有帐户。 这些是在数据库中重复的行。 因此,例如:
Customer c;
c.CustomerName = "Kevin";
c.CustomerAccount.Add(new CustomerAccount() {
AccountId = existingAccountId,
Account = existingAccount
}
AddCustomer(c);
在此示例中,existedAccount被复制。
我知道这与DataContext.Attach()方法有关。 但是,如果添加了多个CustomerAccount关系,那将不起作用。 (ObjectStateManager中已经存在具有相同键的对象。)
提前感谢。
不要创建CustomerAccount的新实例。 您必须从数据库中重新加载它并使用Context中的对象。
Customer c;
c.CustomerName = "Kevin";
var customerAccount = DataContext.CustomerAccount.First( c => c.AccountId == existingAccountId)
c.CustomerAccount = customerAccount;
DataContext.Customer.Add(c);
DataContext.SaveChanges();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.