1110
1110

Reputation: 6829

How to refactor EF data access code to avoid context issues

I am trying to get and update EF object but I am getting error:

Additional information: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

I understand what is the issue. But how to properly write data access methods to avoid issues like this?

var store = (new StoresRepository(connectionString)).GetStore(1);
// Change store object
(new StoresRepository(connectionString)).Update(store);

Data access code:

public class StoresRepository
    {
        AppDbContext context;

        public StoresRepository(string connectionString)
        {
            context = new AppDbContext(connectionString);
        }

        public Store GetStore(int storeId)
        {
            var store = context.Stores.SingleOrDefault(x=>x.StoreId == storeId);

            return store;
        }
        public void Update(Store store)
        {
            context.Stores.Attach(store);

            context.SaveChanges();
        }

Upvotes: 0

Views: 64

Answers (1)

krillgar
krillgar

Reputation: 12805

Create a Repository object instead of creating new ones every time.

var repo = new StoresRepository(connectionString);

var store = repo.GetStore(1);

repo.Update(store);

Upvotes: 1

Related Questions