The context cannot be used while the model is being created

今天在使用 EF 的Code First 过程中,更新数据到数据库时,

执行到  context.UserPermission.Add(permission);

时提示错误信息:提供程序未返回 ProviderManifestToken 字符串。(用户未处理ProviderIncompatibleException)。

根据网上提示在 web.config 中添加

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

(在此之前,没有在数据库中配置连接字符串)

其中 name 为 项目中定义的上下文 名称。

添加完成后,重新运行程序。

原本打算跟踪程序,看上下文(context)赋值是否成功,

但是运行至:   using (var context = new EFDBContext()) 

提示异常信息: The context cannot be used while the model is being created.

查阅了网上的提供的信息:

一种说法是:书写的连接字符串有问题,重新检查后从SQL server使用 .\SQLEXPRESS 登录,发现正常登录。

然后使用(local)也可以正常登录。

另一种说法是 :


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

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.


译文的大概意思是:


过去遇到问题通常由于使用最新版本+ 引用问题

错误另一个原因可以创建上下文第一因此导致模型创建另一个上下文创建一个单独线程必须等待其他上下文实例创建模型创建完成

于是更换连接字符串,重新启动程序(在此之前清理缓存信息);

发现可以正常通过。


This issue usually arises when you have logic that tries to use the context inside OnModelCreating, any chance you can post up the code from your OnModelCreating?


根据这个人说法,当你有尝试使用 OnModelCreating,您可以从您的 OnModelCreating 代码发布里面涉及上下文的逻辑,通常也会出现这个问题。


中间需要保证,上下文初始化的时候,所有延迟加载的项必须与程序中一致,如果加载过程中出现异常,需要清理上下文已加载的内容,然后重新初始化。






评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值