简体   繁体   English

实体框架:添加新对象将导致重复

[英]Entity framework: adding new objects results in duplicates

I'm developing a 3-tier WinForms application. 我正在开发一个三层WinForms应用程序。 But when I try to add a new object to the database, some objects get duplicated. 但是,当我尝试向数据库中添加新对象时,某些对象会重复。

Classes: 类别:

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; }
}

This is the code I use to add the Customer object to the database: 这是我用来将Customer对象添加到数据库中的代码:

 DataContext.CustomerSet.Add(customer);
 DataContext.SaveChanges();

The accounts that are added to the customer are existing accounts. 添加到客户的帐户是现有帐户。 And these are the rows that are duplicated in the database. 这些是在数据库中重复的行。 So for example: 因此,例如:

Customer c;
c.CustomerName = "Kevin";

c.CustomerAccount.Add(new CustomerAccount() {
    AccountId = existingAccountId,
    Account = existingAccount
}

AddCustomer(c);

In this example, existingAccount gets duplicated. 在此示例中,existedAccount被复制。

I know it's something with the DataContext.Attach() method. 我知道这与DataContext.Attach()方法有关。 But that doesn't work when there is more than one CustomerAccount relation added. 但是,如果添加了多个CustomerAccount关系,那将不起作用。 (An object with the same key already exists in the ObjectStateManager.) (ObjectStateManager中已经存在具有相同键的对象。)

Thanx in advance. 提前感谢。

Don't create a new instance of CustomerAccount. 不要创建CustomerAccount的新实例。 you must reload it from your database and work with the object from the Context. 您必须从数据库中重新加载它并使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM