I am trying to create a console application where I am trying to use Entity Framework to dynamically create database and tables to store the data. However, when I am trying to add data to my DbSet
. I am getting the following error.
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.
I have referred to other posts with similar error but none of the solutions worked. This is a single threaded application.
The error occurs at line
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();
}
...
}
My context:
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; }
}
Model
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>
Using VS2015, I was getting this error when debugging (F5). After simply stopping the debugger and restarting the problem went away.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With