我正在开发一个3层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);
在此示例中,existingAccount会重复。
我知道它与DataContext.Attach()方法有关。但是,如果添加了多个CustomerAccount关系,则无效。 (ObjectStateManager中已存在具有相同键的对象。)
提前完成。
答案 0 :(得分:1)
不要创建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();