gpt4 book ai didi

c# - Entity Framework - 创建模型时无法使用上下文

转载 作者:太空狗 更新时间:2023-10-30 00:23:27 24 4
gpt4 key购买 nike

我正在尝试创建一个控制台应用程序,我正在尝试使用 Entity Framework 动态创建数据库和表来存储数据。但是,当我尝试将数据添加到我的 DbSet 时。我收到以下错误。

An unhandled exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll

Additional information: 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.

我引用了其他有类似错误的帖子,但没有一个解决方案有效。这是一个单线程应用程序。

错误发生在行

this.context.Environments.Add(entity)

DataSource.cs

public class DataSource
{
private static DataSource instance;

public DataSource()
{
this.context = new CounterContext();
}

public static DataSource Instance
{
get
{
return instance ?? (instance = new DataSource());
}
}

private CounterContext context;

public void AddCockpitEnvironmentDetails(IList<Environment> environmentList)
{
foreach (var entity in environmentList)
{
this.context.Environments.Add(entity);
}

this.context.SaveChanges();
}
...
}

我的背景:

public class CounterContext : DbContext
{
public CounterContext()
: base("name=CounterDbString")
{
Database.SetInitializer<CounterContext>(new CreateDatabaseIfNotExists<CounterContext>());
}
public DbSet<CounterData> CounterDetails { get; set; }

public DbSet<Environment> Environments { get; set; }
}

型号

public class Environment
{
[Key]
public Guid Id { get; set; }
public string EnvironmentName { get; set; }
public string EnvironmentNotes { get; set; }

public virtual ICollection<CounterDetail> CounterDetails { get; set; }
};

public class CounterData
{
[Key]
[Column(Order = 1)]
public DateTime counterTime { get; set; }
[Key]
[Column(Order = 2)]
public int counterName { get; set; }
[Key]
[Column(Order = 3)]
public Guid EnvId {get; set;}
public int count { get; set; }

[ForeignKey("EnvId")]
public virtual CockpitEnvironment Machine { get; set; }
}

App.config:

<connectionStrings>
<add name="CounterDbString"
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Counters_Test;Integrated Security=True;Connect Timeout=30"
providerName="System.Data.SqlClient"/>
</connectionStrings>

最佳答案

使用 VS2015,我在调试 (F5) 时遇到此错误。简单地停止调试器并重新启动后,问题就消失了。

关于c# - Entity Framework - 创建模型时无法使用上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38901268/

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