C# 创建模型时无法使用上下文
在我的应用程序中,我收到以下错误: 创建模型时无法使用上下文 我不知道这是什么意思。我做的每件事都很正常,通常都能正常工作,但这一次不行。下面是我的代码: App.config:C# 创建模型时无法使用上下文,c#,entity-framework,C#,Entity Framework,在我的应用程序中,我收到以下错误: 创建模型时无法使用上下文 我不知道这是什么意思。我做的每件事都很正常,通常都能正常工作,但这一次不行。下面是我的代码: App.config: Products.cs: class Products { public int ProductID { get; set; } public string ProductName { get; set; } } DatabaseContext.cs: class DatabaseContext
Products.cs:
class Products
{
public int ProductID { get; set; }
public string ProductName { get; set; }
}
DatabaseContext.cs:
class DatabaseContext : DbContext
{
public DbSet<Products> Products { get; set; }
}
该行在isvar products=context.products.ToList()上失败代码>
你知道这是什么原因吗?我已经在我的数据库中设置了2个产品,所以它应该输出它们
编辑
这是我的整个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>
我以前遇到过这个问题,通常是因为没有使用最新版本+引用问题
尝试从NuGet获取所有项目的最新EF版本,看看错误是否消失:
更新
此错误的另一个原因可能是,当您第一次创建上下文并因此导致创建模型时,您在单独的线程上创建了另一个上下文。在模型创建完成后,您必须等待创建其他上下文实例。使用数据库目录名称添加DatabaseContext构造函数
public class DatabaseContext : DbContext {
public DbSet<Products> Products { get; set; }
public DatabaseContext() : base("ProjectCode") {}
}
如果仍然有错误,请尝试将您的项目目标框架更改为使用.net framework 4.0。在您的App.Config文件的ConnectionString下,您有一个正斜杠(./SQLEXPRESS)。将此更改为反斜杠。\SQLEXPRESS如下所示:
<add name="DatabaseContext" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=ProjectCode;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
我遇到了同样的问题,并使用以下代码解决了它:
Database.SetInitializer<EntitiesName>(null);
Database.SetInitializer(null);
我通过添加
MultipleActiveResultSets=true
到my EF连接字符串
我通过添加这个多线程连接参数修复了它。我也有同样的问题。我检查了连接字符串,并确保SQL Server服务正在运行以解决此问题。我也有此错误,但可以通过在每个线程内声明局部变量上下文而不是使用我全局声明的上下文来解决此问题
Parallel.ForEach(myList, l=>
{
MyContext _db = new MyContext();
// do some stuff....
_db.Model.Add(....);
_db.SaveChanges();
});
请确保在连接字符串中如上所述设置MultipleActiveResultSets=true。我知道这是一张旧票证,但我也可以帮助其他有相同问题的人,在我的情况下,我没有在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>
e、 g
这应该行得通
您好。在我的例子中,我是先使用代码的,而我忘记了为最后的更改更新数据库。上下文和数据库必须相同。如果没有,请在package manager中输入以下代码
Update-Database
通过以下方式解决:
我在我的申请中遇到了同样的问题,并通过使用下面的解决方法解决了这个问题
验证您的模型名和表名,并且应该匹配
模型中使用的数据类型和列名与数据库表列名/数据类型应匹配
在上下文类中使用以下代码
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; }
}
Public类MVCRepositoryContext:DbContext
{
静态MVCRepositoryContext()
{
Database.SetInitializer(null);
}
公共MVCRepositoryContext():基(“MVCRepositoryContext”){}
公共虚拟数据库集客户{get;set;}
公共虚拟数据库集书籍{get;set;}
公共虚拟数据库集作者{get;set;}
}
我今天也遇到了同样的问题
在我的例子中,重新启动Visual Studio解决了这个问题 代码中的一个错误是始终在使用
块中使用DB上下文。DB上下文不是线程安全的。每个请求使用一个瞬间更好我也有同样的问题。。。但是,我的问题是我使用的是自定义角色提供程序。此角色提供程序有一个对我的上下文的引用,该引用在应用程序的整个生命周期内保持打开状态。在多个web浏览器试图同时发出请求之前,这不是一个问题
我的解决方案是在每个重写方法的自定义RoleProvider中创建一个新上下文,并通过using语句进行处置
using(var ctx = new Entities())
{
//do stuff
}
因此,基本上,如果您遇到这个错误,您需要查看堆栈跟踪,查看错误发生在哪个方法/文件上,然后每次修改有问题的方法/类以处理上下文
在我的例子中,我使用了Ninject DI,并在自定义角色提供程序和自定义actionfilter中实现了DI。为了解决多个线程访问同一上下文的问题,我放弃了这些类中的DI,直接为每个类创建一个新上下文 1-确保连接字符串具有反斜杠而不是正斜杠:
connectionString="Data Source=.\SQLEXPRESS ....
2-向连接字符串添加MultipleActiveResultSets=true
3-对我来说,这是因为我的DbContext
类有多个构造函数:
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace MyProject
{
public partial class Model1 : DbContext
{
// I had to comment out this one ...
//public Model1()
// : base("name=Model1")
//{
//}
public Model1(bool enableLazyLoading = true)
: base("name=Model1")
{
//Database.SetInitializer<Model1>(new CreateDatabaseIfNotExists<Model1>());
//this.Configuration.LazyLoadingEnabled = false;
Database.SetInitializer<Model1>(null);
this.Configuration.ProxyCreationEnabled = false;
((IObjectContextAdapter)this).ObjectContext.ContextOptions.LazyLoadingEnabled = enableLazyLoading;
((IObjectContextAdapter)this).ObjectContext.ContextOptions.ProxyCreationEnabled = enableLazyLoading;
}
public virtual DbSet<Product> Products { get; set; }
// ...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// ...
}
}
}
使用System.Data.Entity;
使用System.Data.Entity.Infrastructure;
使用System.Data.Entity.ModelConfiguration.Conventions;
名称空间MyProject
{
公共部分类Model1:DbContext
{
//我不得不把这一条注释掉。。。
//公共模型1()
//:base(“name=Model1”)
//{
//}
公共模型1(bool enableLazyLoading=true)
:base(“name=Model1”)
{
//SetInitializer(新的CreateDatabaseIfNotExists());
//this.Configuration.LazyLoadingEnabled=false;
Database.SetInitializer(null);
this.Configuration.ProxyCreationEnabled=false;
((IObjectContextAdapter)this).ObjectContext.ContextOptions.LazyLoadingEnabled=enableLazyLoading;
((IObjectContextAdapter)this).ObjectContext.ContextOptions.ProxyCreationEnabled=enableLazyLoading;
}
公共虚拟数据库集产品{get;set;}
using(var ctx = new Entities())
{
//do stuff
}
connectionString="Data Source=.\SQLEXPRESS ....
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace MyProject
{
public partial class Model1 : DbContext
{
// I had to comment out this one ...
//public Model1()
// : base("name=Model1")
//{
//}
public Model1(bool enableLazyLoading = true)
: base("name=Model1")
{
//Database.SetInitializer<Model1>(new CreateDatabaseIfNotExists<Model1>());
//this.Configuration.LazyLoadingEnabled = false;
Database.SetInitializer<Model1>(null);
this.Configuration.ProxyCreationEnabled = false;
((IObjectContextAdapter)this).ObjectContext.ContextOptions.LazyLoadingEnabled = enableLazyLoading;
((IObjectContextAdapter)this).ObjectContext.ContextOptions.ProxyCreationEnabled = enableLazyLoading;
}
public virtual DbSet<Product> Products { get; set; }
// ...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// ...
}
}
}