Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#实体框架-上下文不能与工作单元存储库模式一起使用_C#_Asp.net Mvc_Entity Framework - Fatal编程技术网

C#实体框架-上下文不能与工作单元存储库模式一起使用

C#实体框架-上下文不能与工作单元存储库模式一起使用,c#,asp.net-mvc,entity-framework,C#,Asp.net Mvc,Entity Framework,我正在尝试在我的ASP.NET MVC应用程序中实现工作单元和存储库模式,如前所述 我收到以下错误: Value cannot be null. Parameter name: entitySet { "The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating

我正在尝试在我的ASP.NET MVC应用程序中实现工作单元和存储库模式,如前所述

我收到以下错误:

Value cannot be null.
Parameter name: entitySet
{
    "The context cannot be used while the model is being created. This exception may be
    thrown if the context is used inside the OnModelCreating method or if the same context
    instance is accessed by multiple threads concurrently. Note that instance members of
    DbContext and related classes are not guaranteed to be thread safe."
}

System.SystemException { System.InvalidOperationException }
Value cannot be null.
Parameter name: entitySet
在查询过程中。在进行一些调试之后,我注意到我的
DBSet
类抛出了以下错误:

Value cannot be null.
Parameter name: entitySet
{
    "The context cannot be used while the model is being created. This exception may be
    thrown if the context is used inside the OnModelCreating method or if the same context
    instance is accessed by multiple threads concurrently. Note that instance members of
    DbContext and related classes are not guaranteed to be thread safe."
}

System.SystemException { System.InvalidOperationException }
Value cannot be null.
Parameter name: entitySet
我已经查看了堆栈溢出,但找不到解决方案。我使用了“先从数据库编码”的方法。我检查了我的连接字符串,它似乎是正确的。我在
packages.config
文件中定义的实体版本是6.1.3。我已经尝试注释了
DbContext
类中的一些关系。其定义如下:

public partial class BKTrainerContext : DbContext
{
    public BKTrainerContext()
        : base("name=BKTrainerContext")
    {
    }

    public virtual DbSet<AccessLevel> AccessLevels { get; set; }
    public virtual DbSet<BuildCardCategory> BuildCardCategories { get; set; }
    public virtual DbSet<BuildCard> BuildCards { get; set; }
    public virtual DbSet<Manager> Managers { get; set; }
    public virtual DbSet<SliderImage> SliderImages { get; set; }
    public virtual DbSet<StoreMessage> StoreMessages { get; set; }
    public virtual DbSet<Store> Stores { get; set; }
    public virtual DbSet<Video> Videos { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<AccessLevel>()
            .HasMany(e => e.Managers)
            .WithRequired(e => e.AccessLevel1)
            .HasForeignKey(e => e.AccessLevel)
            .WillCascadeOnDelete(false);

        modelBuilder.Entity<BuildCardCategory>()
            .HasMany(e => e.BuildCards)
            .WithRequired(e => e.BuildCardCategory1)
            .HasForeignKey(e => e.BuildCardCategory)
            .WillCascadeOnDelete(false);

        modelBuilder.Entity<Manager>()
            .HasMany(e => e.StoreMessages)
            .WithRequired(e => e.Manager)
            .HasForeignKey(e => e.MessageAuthor)
            .WillCascadeOnDelete(false);

        modelBuilder.Entity<Manager>()
            .HasMany(e => e.Stores)
            .WithRequired(e => e.Manager)
            .WillCascadeOnDelete(false);

        modelBuilder.Entity<StoreMessage>()
            .Property(e => e.MessageBody)
            .IsUnicode(false);

        modelBuilder.Entity<StoreMessage>()
            .HasMany(e => e.Stores)
            .WithMany(e => e.StoreMessages)
            .Map(m => m.ToTable("MessagesStores").MapLeftKey("MessageID").MapRightKey("StoreID"));
    }
}
public class UnitOfWork : IUnitOfWork
{

    private BKTrainerContext dbContext = new BKTrainerContext();
    private GenericRepo<BuildCard> buildCardRepo;
    private GenericRepo<BuildCardCategory> buildCardCategoryRepo;
    private GenericRepo<Manager> managerRepo;
    private GenericRepo<StoreMessage> messageRepo;
    private GenericRepo<SliderImage> sliderRepo;
    private GenericRepo<Store> storeRepo;
    private GenericRepo<Video> videoRepo;

    private bool disposed = false;

    public GenericRepo<BuildCard> BuildCardRepo
    {
        get
        {
            if (this.buildCardRepo == null) { buildCardRepo = new GenericRepo<BuildCard>(dbContext); }
            return buildCardRepo;
        }
    }


    public GenericRepo<BuildCardCategory> BuildCardCategoriesRepo
    {
        get
        {
            if (this.buildCardCategoryRepo == null) { buildCardCategoryRepo = new GenericRepo<BuildCardCategory>(dbContext); }
            return buildCardCategoryRepo;
        }
    }


    public GenericRepo<Manager> ManagerRepo
    {
        get
        {
            if (this.managerRepo == null) { managerRepo = new GenericRepo<Manager>(dbContext); }
            return managerRepo;
        }
    }


    public GenericRepo<StoreMessage> MessageRepo
    {
        get
        {
            if (this.messageRepo == null) { messageRepo = new GenericRepo<StoreMessage>(dbContext); }
            return messageRepo;
        }
    }


    public GenericRepo<SliderImage> SliderRepo
    {
        get
        {
            if (this.sliderRepo == null) { sliderRepo= new GenericRepo<SliderImage>(dbContext); }
            return sliderRepo;
        }
    }


    public GenericRepo<Store> StoreRepo
    {
        get
        {
            if (this.storeRepo == null) { storeRepo= new GenericRepo<Store>(dbContext); }
            return storeRepo;
        }
    }


    public GenericRepo<Video> VideoRepo
    {
        get
        {
            if (this.videoRepo == null) {videoRepo = new GenericRepo<Video>(dbContext); }
            return videoRepo;
        }
    }

    public void Save()
    {
        dbContext.SaveChanges();
    }

    protected virtual void Dispose(bool disposing) {
        if (!this.disposed)
        {
            if (disposing)
            {
                dbContext.Dispose();
            }
        }
        this.disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}
我正在使用Unity将其注入控制器

public class HomeController : Controller
{

    private IUnitOfWork worker;

    public HomeController(IUnitOfWork unit)
    {
        this.worker = unit;
    }



    public ActionResult Index(bool failedLogin = false)
    {
        IndexViewModel vm = new IndexViewModel();
        vm.invalidLogin = failedLogin;
        return View(vm);
    }

    [HttpPost]
    public ActionResult AttemptLogin(string userName, string password)
    {

       List<Store> stores = worker.StoreRepo.Get().ToList();
       Store store = worker.StoreRepo.Get(u => u.Username == userName && u.Password == password).FirstOrDefault();
        if (stores != null)
        {
            Session["UserLevel"] = 0;
            Session["UserID"] = store.ID;
            return RedirectToAction("Index", "User");
        }
        else
        {
            Manager manager = worker.ManagerRepo.Get(m => m.Username == userName && m.Password == password).FirstOrDefault();
            if (manager != null)
            {
                Session["UserLevel"] = manager.AccessLevel;
                Session["UserID"] = manager.ID;
                return RedirectToAction("Index", "Admin");
            }
            else
            {
                return RedirectToAction("Index", new { failedLogin = true });
            }
        }
    }
}

只需更改
注册表类型
方法中的一行:

container.RegisterType<IUnitOfWork, UnitOfWork>(new TransientLifetimeManager());
container.RegisterType(新的TransientLifetimeManager());
或者试着换成

container.RegisterType<IUnitOfWork, UnitOfWork>(new PerThreadLifetimeManager());
container.RegisterType(新的PerThreadLifetimeManager());

这里发生的情况是,多个线程试图共享同一个
DbContext
。第二个线程尝试在模型仍在第一个线程上构建时查询模型。解决方案是确保没有两个线程共享相同的
DbContext
。如果不同线程上的
DbContext
不同,那么每个线程都会自己构建和查询模型。

最终解决了这个问题。我忘了在类中将客户属性标记为[NotMapped]

    public HttpPostedFileBase cardImg { get; set; }
修正只涉及添加属性

    [NotMapped]
    public HttpPostedFileBase cardImg { get; set; }
我的印象是以下错误:

Value cannot be null.
Parameter name: entitySet
{
    "The context cannot be used while the model is being created. This exception may be
    thrown if the context is used inside the OnModelCreating method or if the same context
    instance is accessed by multiple threads concurrently. Note that instance members of
    DbContext and related classes are not guaranteed to be thread safe."
}

System.SystemException { System.InvalidOperationException }
Value cannot be null.
Parameter name: entitySet
是由上下文问题引起的。显然,情况恰恰相反;空参数问题导致“无法使用上下文”错误。关于解决与null entitySet参数相关的问题(这可能导致上述上下文问题)的良好总结


解决方案很简单,但是,根据错误消息,这不是我最初的猜测。因此,我希望有人能够从我愚蠢的错误中获得一些有用的见解。

IUnitOfWork有什么范围?该错误看起来像是将相同的
i工作单元
注入到不同的操作/线程中。在控制器中?它是一个私有类级别变量。这是一个公共接口。希望这就是你要问的。你能分享一下你的配置IUnitOfWork生存期的代码吗?@KellyMarchewa请在你注册依赖注入的
IUnitOfWork
的地方发帖。这就是定义它的生命周期/范围的地方。我添加了配置Unity的类。我希望这就是你的意思。谢谢谢谢你的回答。我尝试了上面的更改,但不幸的是它仍然给出相同的错误。还有其他建议吗?再次感谢。