Kevin
Kevin

Reputation: 63

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.

Upvotes: 0

Views: 596

Answers (1)

David C
David C

Reputation: 678

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();

Upvotes: 1

Related Questions