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.
existingAccountId.Accountproperty, but you don't have to set both. When you fetch Customer from the database you can access theirCustomerAccount.Accountand theAccountdata will be available.Accountto the context theCustomeris attached to and setCustomerAccount.Accountafter all. (In which case you don't have to setAccountId).