views:

144

answers:

1

I'm using code-first pattern for database layer.

I have two POCO classes:

public class Order
{
    [Key]
    public int OrderId { get; set; }
    public virtual ICollection<Item> Items { get; set; }
    // other fields
}

and

public class Item
{
    [Key]
    public int ItemId { get; set; }
    public virtual ICollection<Order> Orders { get; set; }
    // other fields
}

Then I have data context class:

public class DataContext : DbContext
{
    public DbSet<Item> Items { get; set; }
    public DbSet<Order> Orders { get; set; }
}

And I have an "repository" class:

public class OrderRepository
{
    private DataContext dataContext = new DataContext();
    public void Save(Order entity)
    {
        entity.OrderDate = System.DateTime.Now;
        dataContext.Orders.Add(entity);
        dataContext.SaveChanges();
    }
}

When I call this OrderRepository.Save method I get an error: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

In database I have a table Items, Orders and Items_Orders...I google-d a lot for this error and for EF many-to-many save, but I haven't find anything useful which would help me, because I couldn't find a sample for Code-First principle.

Thanks!

+2  A: 

You probably have other entities (from other repositories?) which came from other DataContexts related to your Order entity. That would cause the error you're seeing.

All repositories should share the same DataContext during a unit of work. You typically do this with constructor injection, like this:

public class OrderRepository
{
    private readonly DataContext dataContext;
    public void Save(Order entity)
    {
        entity.OrderDate = System.DateTime.Now;
        dataContext.Orders.Add(entity);
        dataContext.SaveChanges();
    }

    public OrderRepository(DataContext dataContext)
    {
        this.dataContext = dataContext;
    }
}
Craig Stuntz
Thanks for the answer. How could I create a constructor injection for DataContext class?
zigomir
See updated answer. Then use a single `DataContext` for all repositories in a UOW.
Craig Stuntz
Thank you, that's it! :) Can you recommend me an Entity Framework 4 book/site/blog with fundamental things that everyone who uses it should know?
zigomir
I'm the wrong person to ask. I've never read any EF books. But Mark Seeman's *Dependency Injection in .NET* covers EF and MVC integration well.
Craig Stuntz