gpt4 book ai didi

c# - Entity Framework 6 异常 : "The context cannot be used while the model is being created"

转载 作者:太空狗 更新时间:2023-10-29 19:46:47 25 4
gpt4 key购买 nike

当我从旧式的 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 of DbContext 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com