具有通用存储库和工作单元存储的实体框架显示旧数据

时间:2013-10-26 13:11:20

标签: c# entity-framework entity-framework-5 repository-pattern

我正在忙着定制的CMS和网站。 CMS和网站共享相同的数据层,数据层使用通用存储库模式与工作单元存储区。

当我查看网站上有简单文字行的页面时,会出现问题。此行文本在CMS中编辑。编辑此行文本并将其保存在CMS中时,我看到正在修改的实体,我也看到了数据库中的更改。 但是,在通过CMS更改这一小段文本然后刷新网站页面后,我仍然会看到旧文本。

我能够显示新的,已更改的文本的唯一方法是重新启动IIS,在web.config中添加空格并保存,以便回收应用程序池。所以在我看来它与实体上下文的缓存有关。

下面是我的通用存储库代码和我的工作单元代码。我认为问题在于其中一个问题,并且某种程度上需要更新实体上下文的缓存或者需要重新加载实体。我可以做些什么来解决这个问题?

信息:工作单元基于this文章。并且网站和CMS在我的本地开发PC上的单独IIS应用程序池中运行

GenericRepository.cs

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Data.Objects;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using CORE.Model;
using CORE.RepositoryInterfaces;

namespace CORE.Repositories
{

    public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
    {
        #region Implementation of IRepository<TEntity>

        //private readonly myContext _context;
        private readonly DbSet<TEntity> _dbSet;

        public GenericRepository()
        {
            //_context = new myContext();
            //_dbSet = _context.Set<TEntity>();

            _dbSet = DataLayer.Instance.Context.Set<TEntity>();
        }

        /// <summary>
        /// Inserts a new object into the database
        /// </summary>
        /// <param name="entity">The entity to insert</param>
        public void Insert(TEntity entity)
        {
            _dbSet.Add(entity);
        }

        /// <summary>
        /// Deletes the specified entity from the database
        /// </summary>
        /// <param name="entity">The object to delete</param>
        public void Delete(TEntity entity)
        {
            if (DataLayer.Instance.Context.Entry(entity).State == System.Data.EntityState.Detached)
            {
                _dbSet.Attach(entity);
            }

            _dbSet.Remove(entity);
        }

        /// <summary>
        /// Saves all pending chances to the database
        /// </summary>
        public void Save()
        {
            try
            {
                DataLayer.Instance.Context.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                //foreach (var eve in e.EntityValidationErrors)
                //{
                //    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                //        eve.Entry.Entity.GetType().Name, eve.Entry.State);
                //    foreach (var ve in eve.ValidationErrors)
                //    {
                //        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                //            ve.PropertyName, ve.ErrorMessage);
                //    }
                //}
                //throw;

                //Log all errors to an temp file.
                //TODO: Implement NLog
                var outputLines = new List<string>();
                foreach (var eve in e.EntityValidationErrors)
                {
                    outputLines.Add(string.Format(
                        "{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:",
                        DateTime.Now, eve.Entry.Entity.GetType().Name, eve.Entry.State));

                    foreach (var ve in eve.ValidationErrors)
                    {
                        outputLines.Add(string.Format(
                            "- Property: \"{0}\", Error: \"{1}\"",
                            ve.PropertyName, ve.ErrorMessage));
                    }
                }
                File.AppendAllLines(@"c:\temp\errors.txt", outputLines);

                throw;
            }
        }

        /// <summary>
        /// Retrieves the first object matching the specified query.
        /// </summary>
        /// <param name="where">The where condition to use</param>
        /// <returns>The first matching object, null of none found</returns>
        public TEntity First(Expression<Func<TEntity, bool>> @where)
        {
            return _dbSet.FirstOrDefault(where);
        }

        /// <summary>
        /// Gets a list of all objects
        /// </summary>
        /// <returns>An strong typed list of objects</returns>
        public IEnumerable<TEntity> GetAll()
        {
            return _dbSet.AsEnumerable();
        }

        /// <summary>
        /// Returns ans iQueryable of the matching type
        /// </summary>
        /// <returns>iQueryable</returns>
        public IQueryable<TEntity> AsQueryable()
        {
            return _dbSet.AsQueryable();
        }

        //public void Dispose()
        //{
        //    DataLayer.Instance.Context.Dispose();
        //    GC.SuppressFinalize(this);
        //}
        #endregion
    }
}

UnitOfWorkStore.CS

using System.Runtime.Remoting.Messaging;
using System.Web;

namespace CORE
{
    /// <summary>
    /// Utility class for storing objects pertinent to a unit of work.
    /// </summary>
    public static class UnitOfWorkStore
    {
        /// <summary>
        /// Retrieve an object from this store via unique key.
        /// Will return null if it doesn't exist in the store.
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static object GetData(string key)
        {
            if (HttpContext.Current != null)
                return HttpContext.Current.Items[key];
            return CallContext.GetData(key);
        }


        /// <summary>
        /// Put an item in this store, by unique key.
        /// </summary>
        /// <param name="key"></param>
        /// <param name="data"></param>
        public static void SetData(string key, object data)
        {
            if (HttpContext.Current != null)
                HttpContext.Current.Items[key] = data;
            else
                CallContext.SetData(key, data);
        }

    }
}

DataLayer.cs

using System;
using CORE.Model;

namespace CORE
{
    /// <summary>
    /// This is the data access layer management class.
    /// See 
    /// </summary>
    public sealed class DataLayer : IDisposable
    {
        /// <summary>
        /// This is our key to store an instance of this class in the <see cref="UnitOfWorkStore" />.
        /// This is used in the <see cref="Instance" /> property.
        /// </summary>
        private const string UowInstanceKey = "MyContext_Instance";

        /// <summary>
        /// This is used for thread-safety when creating the instance of this class to be stored in
        /// the UnitOfWorkStore.
        /// </summary>
        private static readonly object SObjSync = new object();

        // The DataContext object
        private readonly MyContext _context;



        // ********************************************************************************
        // *** Constructor(s) *************************************************************
        // ********************************************************************************

        /// <summary>
        /// Default constructor.  Creates a new MyEntities DataContext object.
        /// This is hidden (private) because the instance creation is managed as a "unit-of-work", via the
        /// <see cref="Instance" /> property.
        /// </summary>
        private DataLayer()
        {
            _context = new MyContext();
        }



        // ********************************************************************************
        // *** Public properties **********************************************************
        // ********************************************************************************

        /// <summary>
        /// The ObjectContext object that gives us access to our business entities.
        /// Note that this is NOT static.
        /// </summary>
        public BorloContext Context
        {
            get { return _context; }
        }


        /// <summary>
        /// This will get the "one-and-only" instance of the DataLayer that exists for the lifetime of the current "unit of work",
        /// which might be the lifetime of the currently running console application, a Request/Response iteration of an asp.net web app,
        /// an async postback to a web service, etc.
        /// 
        /// This will never return null.  If an instance hasn't been created yet, accessing this property will create one (thread-safe).
        /// This uses the <see cref="UnitOfWorkStore" /> class to store the "one-and-only" instance.
        /// 
        /// This is the instance that is used by all of the DAL's partial entity classes, when they need a reference to a MyEntities context
        /// (DataLayer.Instance.Context).
        /// </summary>
        public static DataLayer Instance
        {
            get
            {
                object instance = UnitOfWorkStore.GetData(UowInstanceKey);

                // Dirty, non-thread safe check
                if (instance == null)
                {
                    lock (SObjSync)
                    {
                        // Thread-safe check, now that we're locked
                        // ReSharper disable ConditionIsAlwaysTrueOrFalse
                        if (instance == null) // Ignore resharper warning that "expression is always true". It's not considering thread-safety.
                        // ReSharper restore ConditionIsAlwaysTrueOrFalse
                        {
                            // Create a new instance of the DataLayer management class, and store it in the UnitOfWorkStore,
                            // using the string literal key defined in this class.
                            instance = new DataLayer();
                            UnitOfWorkStore.SetData(UowInstanceKey, instance);
                        }
                    }
                }

                return (DataLayer)instance;
            }
        }

        public void Dispose()
        {
            _context.Dispose();
            GC.SuppressFinalize(this);
        }
    }
}

更新 - 1:通过通用服务使用GenericRepository

CMS服务的用法:

private readonly IGenericService<TextBlock> _textBlockService;

public TextBlockController(): base(new GenericService<ComponentType>(), new GenericService<Blog>())
{
    if (_textBlockService == null)
    {
        _textBlockService = new GenericService<TextBlock>();
    }
}

通过HTML帮助程序使用服务前端

public static class RenderEngine
{
    private static readonly IGenericService<Component> ComponentService;
    private static readonly IGenericService<TextBlock> TextBlockService;

    /// <summary>
    /// Constructor for this class.
    /// </summary>
    static RenderEngine()
    {
        if (ComponentService == null)
        {
            ComponentService = new GenericService<Component>();
        }
        if (TextBlockService == null)
        {
            TextBlockService = new GenericService<TextBlock>();
        }
    }

    //Html helper method does something like TekstBlokService.First(/*linq statement*/)
}

更新 - 2:添加了通用服务的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using CORE.Repositories;
using CORE.RepositoryInterfaces;
using BLL.ServiceInterfaces;

namespace BLL.Services
{

    public class GenericService<T> : IGenericService<T> where T : class
    {
        #region properties
        protected readonly IGenericRepository<T> MyRepository;
        #endregion

        #region constructor
        //[Inject]
        public GenericService(IGenericRepository<T> repository)
        {
            MyRepository = repository;
        }

        //public GenericService()
        //{
        //    if (Repository == null)
        //    {
        //        Repository = new Repository<T>();
        //    }

        //}

        ////todo: uitzoeken!
        public GenericService()
            : this(new GenericRepository<T>())
        {

        }

        #endregion

        #region Implementation of IService<T>

        /// <summary>
        /// Inserts a new object into the database
        /// </summary>
        /// <param name="entity">The entity to insert</param>
        public void Insert(T entity)
        {
            MyRepository.Insert(entity);
        }

        /// <summary>
        /// Retrieves the first object matching the specified query.
        /// </summary>
        /// <param name="where">The where condition to use</param>
        /// <returns>The first matching object, null of none found</returns>
        public T First(Expression<Func<T, bool>> @where)
        {
            return MyRepository.First(where);
        }

        /// <summary>
        /// Gets a list of all objects
        /// </summary>
        /// <returns>An strong typed list of objects</returns>
        public IEnumerable<T> GetAll()
        {
            return MyRepository.GetAll();
        }

        /// <summary>
        /// Returns ans iQueryable of the matching type
        /// </summary>
        /// <returns>iQueryable</returns>
        public IQueryable<T> AsQueryable()
        {
            return MyRepository.AsQueryable();
        }

        /// <summary>
        /// Deletes the specified entity from the database
        /// </summary>
        /// <param name="entity">The object to delete</param>
        public void Delete(T entity)
        {
            MyRepository.Delete(entity);
        }

        /// <summary>
        /// Saves all pending chances to the database
        /// </summary>
        public void Save()
        {
            MyRepository.Save();
        }

        //protected override void Dispose(bool disposing)
        //{
        //    _movieService.Dispose();
        //    base.Dispose(disposing);
        //}

        #endregion

        //public void Dispose()
        //{
        //    MyRepository.Dispose();
        //    GC.SuppressFinalize(this);
        //}
    }
}

2 个答案:

答案 0 :(得分:2)

问题肯定在这里发现:

public static class RenderEngine
{
    private static readonly IGenericService<Component> ComponentService;
    private static readonly IGenericService<TextBlock> TextBlockService;

    /// <summary>
    /// Constructor for this class.
    /// </summary>
    static RenderEngine()
    {
        if (ComponentService == null)
        {
            ComponentService = new GenericService<Component>();
        }
        if (TextBlockService == null)
        {
            TextBlockService = new GenericService<TextBlock>();
        }
    }

    //Html helper method does something like TekstBlokService.First(/*linq statement*/)
}

假设GenericServiceGenericRepository或持有GenericRepository

使用某些静态字段来引用您的GenericService个实例,保留GenericRepository个实例,这些实例依次保留DBSets个包含的字段(称为_dbSet)及其相关的{{ 1}}。

DataContexts类在GenericRepositories的构造函数中获取DbSets并且永远不再更新它们时,相应的“静态实例”将继续使用与第一个相同的get,这些将在关联的IIS应用程序池的整个生命周期内持续。

这意味着每次收到新的HTTP请求时,您的UnitOfWorkStore及其相关的Datacontext实例都不会续订,因为它们应该是静态DbSets / GenericServices。实际上,使用GenericRepositories来管理HttpContext.Current.Items生命周期表明您要做的是为每个新的HTTP请求创建一个新的。 (这就是你指出的文章的目的)。

让我们试着总结一下:

    只有在重新启动关联的IIS应用程序池时(正如您所报告的那样),才会续订静态DataContext / DataContext引用的
  • GenericServices个实例。
  • GenericRespositories“静态实例”始终在HTTP请求中使用相同的GenericRepositoryDbSets而非新请求,这会导致实体刷新问题。
  • 您最终使用DataContexts“静态实例”获取旧实体和GenericRepositories“新实例”(来自您的控制器)获取最新数据(因为它们的_dbSet字段填充了您的GenericRepositories
  • 提供的新DataContext

要解决问题,有很多解决方案,这里有几个:

  • 请勿将UnitOfWorkStore个引用保存到DBSet
  • 请勿将GenericRepositoriesGenericServices用作静态字段/属性
  • ......以及许多其他人,只要简单地删除或使用静态字段

希望所有这些假设都有助于朝着正确的方向前进。

答案 1 :(得分:0)

尝试context.Entry(<!-- Name -->).Reload();

相关问题