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

时间:2023-11-15 14:18:08

在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)
{ }
}
}