简体   繁体   中英

Entity framework: adding new objects results in duplicates

I'm developing a 3-tier WinForms application. 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:

 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.

I know it's something with the DataContext.Attach() method. But that doesn't work when there is more than one CustomerAccount relation added. (An object with the same key already exists in the ObjectStateManager.)

Thanx in advance.

Don't create a new instance of CustomerAccount. you must reload it from your database and work with the object from the Context.

    Customer c;
    c.CustomerName = "Kevin";

    var customerAccount = DataContext.CustomerAccount.First( c => c.AccountId == existingAccountId)


    c.CustomerAccount = customerAccount;
    DataContext.Customer.Add(c);
    DataContext.SaveChanges();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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