What happend?

I have the following classes with many-to-many relation:

public class Customer 
{
     public HashSet<Invoice> Invoices { get; set; }
}

public class Invoice
{
     public HashSet<Customer> Customers { get; set; }
}

Now, I would like to add existing invoice to the customer:

Invoice inv = new Invoice
    {
        Id = 10
    };

dbContext.Invoices.Attach(inv);
someCustomer.Invoices.Add(inv);

When try to run the snippet written above, the following exception is thrown:

Cannot insert duplicate key into ‘dbo.CustomerInvoices’….

What is the problem?

After spending a couple of minutes on searching solution, it turned out that remedy is very simple:

public class Customer 
{
     public virtual HashSet<Invoice> Invoices { get; set; }
}

Yes, virtual word was the key. Without it, EF is not able to track changes. But why such an error was thrown? Do not know, maybe you guys?


Patryk Wąsiewicz

A very casual blog about programmer's life.