- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
当我从旧式的 ADO.NET 转向 Entity Framework 6 时,我有点陌生,所以请耐心等待。
我正在尝试创建一个新的 WPF MVVM 项目以及一些将直接使用 DBContext
而无需与 EF 6 进行数据绑定(bind)的 WinForms。
使用 Visual Studio 2013 Entity Framework 向导,我通过对我们业务服务器上的当前数据库进行逆向工程创建了代码优先。然后我将数据模型类从上下文中分离出来
这是 DbContext
代码:
namespace EFModels
{
public partial class MyDataContext : DbContext
{
public MyDataContext () : base("name=MyDataContext")
{
}
public virtual DbSet<Calibration> Calibrations { get; set; }
public virtual DbSet<OrderDetail> OrderDetails { get; set; }
public virtual DbSet<OrderHistory> OrderHistories { get; set; }
public virtual DbSet<WorkDetail> WorkDetails { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<WorkDetail>()
.HasMany(e => e.Calibrations)
.WithOptional(e => e.WorkDetail)
.HasForeignKey(e => e.WorkID);
}
}
}
我已经将数据类分隔在一个单独的命名空间中,例如:
namespace MyDataDomain
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
public partial class OrderDetail
{
public OrderDetail()
{
Calibrations = new HashSet<Calibration>();
JournalEntryDatas = new HashSet<JournalEntryData>();
OrderHistories = new HashSet<OrderHistory>();
WorkDetails = new HashSet<WorkDetail>();
}
[Key]
public long OrderID { get; set; }
[StringLength(50)]
public string PONumber { get; set; }
[Column(TypeName = "date")]
public DateTime? Due { get; set; }
[Column(TypeName = "date")]
public DateTime? OrderDate { get; set; }
[Column(TypeName = "date")]
public DateTime? ShipDate { get; set; }
[Column(TypeName = "text")]
public string Comment { get; set; }
public int? EnterByID { get; set; }
public virtual ICollection<Calibration> Calibrations { get; set; }
public virtual ICollection<JournalEntryData> JournalEntryDatas { get; set; }
public virtual ICollection<OrderHistory> OrderHistories { get; set; }
public virtual ICollection<WorkDetail> WorkDetails { get; set; }
}
}
其余的类都是类似的风格,但是当使用外键约束时,它有这样的东西:
public virtual OrderDetail OrderDetail { get; set; }
因为在我们的小世界中,它将围绕着订单。
和 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=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
</startup>
<connectionStrings>
<add name="MyDataContext" connectionString="data source=BIZSERVER\SQL2008R2DB;initial catalog=Company;persist security info=True;user id=DaBossMan;password=none_of_your_damn_business;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient"/>
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
所以当我这样做时:
var context = New MyDataContext();
var list1 = context.JournalEntryDatas.ToList();
var list2 = context.OrderHistories.ToList();
抛出异常:
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 ofDbContext
and related classes are not guaranteed to be thread safe.
我在这里发疯了,想弄清楚我能做什么,我一直在读到也许做一个任务工厂会有帮助,那么我如何使用它从每个表中获取数据,这样我就可以填充列表?
或者我可以使用其他替代方法或解决方法吗?
编辑:这是按要求(由 Andez)提供的完整堆栈跟踪:
System.InvalidOperationException was caught
HResult=-2146233079
Message=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.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()
at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at MichellControls.JournalDataListView.JournalDataListView_Load(Object sender, EventArgs e) in c:\Users\Steve\Projects\Visual Studio 2013\Projects\MyControls\WinFormControls\JournalDataListView.cs:line 35
InnerException:
// (there wasn't any InnerException)
最佳答案
你说你(是) Entity Framework 的新手,所以也许值得指出 DbContext
不应该被共享和重用。通常您会希望在单个工作单元内创建、使用和处置 DbContext
。
换句话说,您不应该“共享”DbContext
(例如,在启动时只创建一个并在多个地方使用它,等等。您提到尝试创建一个“线程安全的”包装器”——你绝对不应该尝试从多个线程访问它(每个操作都有自己的 DbContext)
关于c# - Entity Framework 6 异常 : "The context cannot be used while the model is being created",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32129111/
我在优化 JOIN 以使用复合索引时遇到问题。我的查询是: SELECT p1.id, p1.category_id, p1.tag_id, i.rating FROM products p1
我有一个简单的 SQL 查询,我正在尝试对其进行优化以删除“使用位置;使用临时;使用文件排序”。 这是表格: CREATE TABLE `special_offers` ( `so_id` int
我有一个具有以下结构的应用程序表 app_id VARCHAR(32) NOT NULL, dormant VARCHAR(6) NOT NULL, user_id INT(10) NOT NULL
此查询的正确索引是什么。 我尝试为此查询提供不同的索引组合,但它仍在使用临时文件、文件排序等。 总表数据 - 7,60,346 产品= '连衣裙' - 总行数 = 122 554 CREATE TAB
为什么额外的是“使用where;使用索引”而不是“使用索引”。 CREATE TABLE `pre_count` ( `count_id`
我有一个包含大量记录的数据库,当我使用以下 SQL 加载页面时,速度非常慢。 SELECT goal.title, max(updates.date_updated) as update_sort F
我想知道 Using index condition 和 Using where 之间的区别;使用索引。我认为这两种方法都使用索引来获取第一个结果记录集,并使用 WHERE 条件进行过滤。 Q1。有什
I am using TypeScript 5.2 version, I have following setup:我使用的是TypeScript 5.2版本,我有以下设置: { "
I am using TypeScript 5.2 version, I have following setup:我使用的是TypeScript 5.2版本,我有以下设置: { "
I am using TypeScript 5.2 version, I have following setup:我使用的是TypeScript 5.2版本,我有以下设置: { "
mysql Ver 14.14 Distrib 5.1.58,用于使用 readline 5.1 的 redhat-linux-gnu (x86_64) 我正在接手一个旧项目。我被要求加快速度。我通过
在过去 10 多年左右的时间里,我一直打开数据库 (mysql) 的连接并保持打开状态,直到应用程序关闭。所有查询都在连接上执行。 现在,当我在 Servicestack 网页上看到示例时,我总是看到
我使用 MySQL 为我的站点构建了一个自定义论坛。列表页面本质上是一个包含以下列的表格:主题、上次更新和# Replies。 数据库表有以下列: id name body date topic_id
在mysql中解释的额外字段中你可以得到: 使用索引 使用where;使用索引 两者有什么区别? 为了更好地解释我的问题,我将使用下表: CREATE TABLE `test` ( `id` bi
我经常看到人们在其Haxe代码中使用关键字using。它似乎在import语句之后。 例如,我发现这是一个代码片段: import haxe.macro.Context; import haxe.ma
这个问题在这里已经有了答案: "reduce" or "apply" using logical functions in Clojure (2 个答案) 关闭 8 年前。 “and”似乎是一个宏,
这个问题在这里已经有了答案: "reduce" or "apply" using logical functions in Clojure (2 个答案) 关闭 8 年前。 “and”似乎是一个宏,
我正在考虑在我的应用程序中使用注册表模式来存储指向某些应用程序窗口和 Pane 的弱指针。应用程序的一般结构如下所示。 该应用程序有一个 MainFrame 顶层窗口,其中有几个子 Pane 。可以有
奇怪的是:。似乎a是b或多或少被定义为id(A)==id(B)。用这种方式制造错误很容易:。有些名字出人意料地出现在Else块中。解决方法很简单,我们应该使用ext==‘.mp3’,但是如果ext表面
我遇到了一个我似乎无法解决的 MySQL 问题。为了能够快速执行用于报告目的的 GROUP BY 查询,我已经将几个表非规范化为以下内容(该表由其他表上的触发器维护,我已经同意了与此): DROP T
我是一名优秀的程序员,十分优秀!