C# 创建模型时不能使用上下文

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9750115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:41:49  来源:igfitidea点击:

The context cannot be used while the model is being created

c#entity-framework

提问by CallumVass

In my application I receive the following error:

在我的应用程序中,我收到以下错误:

The context cannot be used while the model is being created.

创建模型时不能使用上下文。

I'm not sure what this means. I have done everything as normal and usually it works but for this one it isnt. Below is my code:

我不确定这意味着什么。我已经像往常一样做了一切,通常它可以工作,但对于这个它不是。下面是我的代码:

App.config:

应用程序配置:

 <connectionStrings>
    <add name="DatabaseContext" connectionString="Data Source=./SQLEXPRESS;Initial Catalog=ProjectCode;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
 </connectionStrings>

Products.cs:

产品.cs:

class Products
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
}

DatabaseContext.cs:

数据库上下文.cs:

class DatabaseContext : DbContext
{
    public DbSet<Products> Products { get; set; }
}

Program.cs:

程序.cs:

DatabaseContext context = new DatabaseContext();

try
{
   var products = context.Products.ToList();

   foreach (var item in products)
   {
      Console.WriteLine(item.ProductID + " : " + item.ProductName);
   }
      Console.ReadLine();
}

The line is fails on is var products = context.Products.ToList();

线路故障是 var products = context.Products.ToList();

Any ideas what could be causing this? I have set up 2 products in my database so it should be outputting them.

任何想法可能导致这种情况?我在我的数据库中设置了 2 个产品,所以它应该输出它们。

EDIT

编辑

Here is my whole App.config file:

这是我的整个 App.config 文件:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.3.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  </configSections>
  <connectionStrings>
    <add name="DatabaseContext" connectionString="Data Source=./SQLEXPRESS;Initial Catalog=ProjectCode;Integrated Security=SSPI;MultipleActiveResultSets=true" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="Data Source=.\SQLEXPRESS; Integrated Security=True; MultipleActiveResultSets=True" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>
</configuration>

采纳答案by mjbates7

In your App.Config file under connectionstrings you had a forward slash (./SQLEXPRESS). Change this to a backslash .\SQLEXPRESS like so:

在连接字符串下的 App.Config 文件中,您有一个正斜杠 (./SQLEXPRESS)。将其更改为反斜杠 .\SQLEXPRESS ,如下所示:

<add name="DatabaseContext" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=ProjectCode;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />

回答by ntziolis

I have experienced this issue in the past and usually it was due not using the latest version + referencing issue.

我过去遇到过这个问题,通常是由于没有使用最新版本 + 引用问题。

Try and get the newest EF version from NuGet for all your projects and see if the error goes away:
http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-released.aspx

尝试从 NuGet 为您的所有项目获取最新的 EF 版本,看看错误是否消失:http:
//blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-released .aspx

UPDATE
Another reason for this error can be that while you create the context the first time and therefore cause the model to be created you create another context on a separate thread. You will have to wait for other context instances to be created after the model creation has completed.

UPDATE
此错误的另一个原因可能是,当您第一次创建上下文并因此导致创建模型时,您在单独的线程上创建了另一个上下文。在模型创建完成后,您将不得不等待其他上下文实例的创建。

回答by AlanCai

Add DatabaseContext constructor with database catalog name.

添加带有数据库目录名称的 DatabaseContext 构造函数。

public class DatabaseContext : DbContext {
    public DbSet<Products> Products { get; set; }

    public DatabaseContext() : base("ProjectCode") {}
}

Change entityframework config in app.config like this.

像这样在 app.config 中更改 entityframework 配置。

<parameter value="Data Source=./SQLEXPRESS;Initial Catalog=ProjectCode;Integrated Security=SSPI;MultipleActiveResultSets=true" />

Add Annotations to Products class. Make sure your database has a "Products" table with tow fields "ProductId" and "ProductName".

向 Products 类添加注释。确保您的数据库有一个包含两个字段“ProductId”和“ProductName”的“Products”表。

class Products {
    [Key]
    public int ProductID { get; set; }
    public string ProductName { get; set; }
}

If still error, try to change you project target framework to use .net framework 4.0.

如果仍然错误,请尝试将您的项目目标框架更改为使用 .net framework 4.0。

回答by Stefan Michev

I had the same issue and solved it using following code:

我遇到了同样的问题并使用以下代码解决了它:

Database.SetInitializer<EntitiesName>(null);

回答by Carlos B. Vasquez

I was able to resolve this issue by adding

我能够通过添加来解决这个问题

MultipleActiveResultSets=true

to the my EF connection string.

到我的 EF 连接字符串。

I fixed it by adding this multiple thread connection parameter.

我通过添加这个多线程连接参数来修复它。

回答by Nabeel

I had same problem. I checked my Connection String and made sure SQL Server Service is running to resolve this issue.

我有同样的问题。我检查了我的连接字符串并确保 SQL Server 服务正在运行以解决此问题。

回答by nurdyguy

I had this error as well but was able to solve it by declaring a local variable context inside of each thread rather than using the one I had declared globally.

我也有这个错误,但能够通过在每个线程内声明一个局部变量上下文而不是使用我全局声明的上下文来解决它。

    Parallel.ForEach(myList, l=>
    {
        MyContext _db = new MyContext();
        // do some stuff....
        _db.Model.Add(....);
        _db.SaveChanges();

    });

Make sure you also set MultipleActiveResultSets=true in your connection string as described above.

确保您还在连接字符串中设置 MultipleActiveResultSets=true ,如上所述。

回答by Deutsche Mexa

I know this is an old ticket, but i could also help to another people with the same problem, in my case, i was not loading a context in a connection string in the app.config file:

我知道这是一张旧票,但我也可以帮助其他有同样问题的人,就我而言,我没有在 app.config 文件的连接字符串中加载上下文:

e.g.

例如

<add name="SalesContext" connectionString="" providerName="System.Data.SqlClient" />

This should works.

这应该有效。

Greetings.

你好。

回答by Ahmet Gokdayi

In my case, i was using Code First, and i had forgotten to update the database for the last changes.The context and the database must be the same. If not, enter the following code in the package manager;

就我而言,我使用的是 Code First,但我忘记为最后一次更改更新数据库。上下文和数据库必须相同。如果没有,在包管理器中输入以下代码;

Update-Database

回答by Jebasingh

Solved by the following:

通过以下方式解决:

I had the same issue in my application and resolved by using the below.

我在我的应用程序中遇到了同样的问题,并通过使用下面的方法解决了。

  1. Verify your Model names and the table names and it should be matched.

  2. Datatype and Column names used in the model and the database table column name/ Datatype should be matched.

  3. use the below code in your Context class

    Public class MVCRepositoryContext : DbContext 
    {
        static MVCRepositoryContext()
        {
            Database.SetInitializer < mvcrepositorycontext > (null);
        }
    
        public MVCRepositoryContext():base("MVCRepositoryContext"){ }
    
        public virtual DbSet<customer> Customers { get; set; }
    
        public virtual DbSet<book> Books { get; set; }
    
        public virtual DbSet<author> Authors { get; set; }
    }
    
  1. 验证您的模型名称和表名称,它应该匹配。

  2. 模型中使用的数据类型和列名与数据库表列名/数据类型应匹配。

  3. 在您的 Context 类中使用以下代码

    Public class MVCRepositoryContext : DbContext 
    {
        static MVCRepositoryContext()
        {
            Database.SetInitializer < mvcrepositorycontext > (null);
        }
    
        public MVCRepositoryContext():base("MVCRepositoryContext"){ }
    
        public virtual DbSet<customer> Customers { get; set; }
    
        public virtual DbSet<book> Books { get; set; }
    
        public virtual DbSet<author> Authors { get; set; }
    }