EF 一个实体对象不能由多个 IEntityChangeTracker 实例引用 解决办法

在DAL层中,建立工厂类

namespace DAL
{
    public static class SysDbContextFactory
    {
        /// <summary>
        /// 从Http上下文中获取EF容器
        /// </summary>
        /// <returns></returns>
        public static SysDbContext GetSysDbContext()
        {
            var context = HttpContext.Current.Items[nameof(SysDbContext)] as SysDbContext;
            if (context == null)
            {
                context = new SysDbContext();
                HttpContext.Current.Items[nameof(SysDbContext)] = context;
            }

            return context as SysDbContext;
        }
    }
}

 

然后在DAL 传入 构造函数

namespace DAL
{
    public class ProductService: EntitryBaseHelper<Product>, IProductService
    {
        public ProductService() : base(SysDbContextFactory.GetSysDbContext())
        {

        }

        public ProductService(SysDbContext _sysDbContext) : base(_sysDbContext)
        {

        }
    }
}

 

posted @ 2019-02-15 09:06  酒沉吟  阅读(456)  评论(0编辑  收藏  举报