简体   繁体   English

如何重构EF数据访问代码以避免上下文问题

[英]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: 我正在尝试获取和更新EF对象,但出现错误:

Additional information: An entity object cannot be referenced by multiple instances of IEntityChangeTracker. 附加信息: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();
        }

Create a Repository object instead of creating new ones every time. 创建一个存储库对象,而不是每次都创建新的对象。

var repo = new StoresRepository(connectionString);

var store = repo.GetStore(1);

repo.Update(store);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM