代码之家  ›  专栏  ›  技术社区  ›  Josh Smeaton

如何在linqtosql中缓存查找数据,并在单独的DataContext中使用这些数据?

  •  1
  • Josh Smeaton  · 技术社区  · 15 年前

    我正在从事的项目有很多与之相关的“查找”数据。因此,在处理此问题的类的第一次实例化时,我将所有查找数据都设置为静态IEnumerable,因此:

    private static IEnumerable<Kiosk> _kiosks;
    private static IEnumerable<Paper> _papers;
    private static IEnumerable<NewsAgent> _newsAgents;
    

    if (_kiosks == null)
       _kiosks = db.Kiosks.Where(k => k.Active).OrderBy(k => k.Order).ToList();
    
    if (_papers == null)
       _papers = db.Papers.Where(p => p.Active).OrderBy(p => p.Name).ToList();
    
    if (_newsAgents == null)
       _newsAgents = db.NewsAgents.Where(n => n.Active).OrderBy(n => n.Order).ToList();
    

    每次实例化这个类时,我都使用全新的DataContext为需要保存的数据类创建新的Linq实体。当我尝试提交这些更改时,出现以下错误:

    "System.NotSupportedException: An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported."
    

    我推测,在单独的DataContext上创建的缓存查找数据导致了这个问题。我认为这应该无关紧要,因为缓存的数据是用ToList持久化的,尽管每个实体都会在内部保存生成它的DataContext。

    那么,如何将缓存的数据持久化以用于新的DataContext?

    1 回复  |  直到 15 年前
        1
  •  1
  •   Neil Barnwell    15 年前

    首先不要缓存从数据上下文返回的实际对象。缓存简单的poco对象,而不是在这些对象上有最基本的信息,然后在更新时使用ID值而不是对象:

    Employee.Status = cachedStatus;
    

    变成

    Employee.StatusID = cachedStatus.ID;