locked
EF Exception:The context cannot be used while the model is being created RRS feed

  • Question

  • User-1845904970 posted

    I'm trying to crate database depening on class variables.

    My classes are defined as

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
     
    namespace CodeFirstAnnotationEntities
    {
        public class Employee
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public int Salary { get; set; }
            public string Job { get; set; }
            public string Last { get; set; }
     
            public Department department;
        }
        public class Department
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public string Location { get; set; }
            public Employee employees;
        }
    }

    My DbContext class is

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Data.Entity;
     
    namespace CodeFirstAnnotationEntities
    {
        public class CodeFirst_AnnotationEntities : DbContext
        {
            public CodeFirst_AnnotationEntities()
                : base("CodeFirstAnnotationConnection")
            {
               
                Database.SetInitializer<CodeFirst_AnnotationEntities>(new CreateDatabaseIfNotExists<CodeFirst_AnnotationEntities>());
                
            }
             
            public DbSet<Employee> Employees { get; set; }
            public DbSet<Department> Departments { get; set; }
         }
    }

    my connection String is

    <add name="CodeFirstAnnotationConnection" connectionString="Data Source=Localhost;Initial Catalog=CodeFirstAnnotation;Integrated Security=true;" providerName="System.Data.SqlClient" />
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
     
    namespace CodeFirstAnnotationEntities
    {
        public partial class WebForm1 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                CodeFirst_AnnotationEntities context = new CodeFirst_AnnotationEntities();
                Employee emp = new Employee() { Name="Scott",Job="admin",Salary=40000,Last="Ben"};
                Department dept = new Department() { Name = "Accounts", Location = "NY" };
                  try{
                    context.Employees.Add(emp);
                    context.Departments.Add(dept);
                    context.SaveChanges();
                }
                catch(Exception ex)
                {
                    
                }
            }
        }
    }

    I've tried using all types of SetInitializer

    The exception I'm getting is: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.



    Wednesday, March 8, 2017 2:12 AM

All replies

  • User527778624 posted

    Hi,

    Try updating your code in Page_Load() like this:

    using(var context = new CodeFirst_AnnotationEntities())
    {
    	context.Database.Initialize(force: false);
    	Employee emp = new Employee() { Name="Scott",Job="admin",Salary=40000,Last="Ben"};
    	Department dept = new Department() { Name = "Accounts", Location = "NY" };
    	try
    	{
    		context.Employees.Add(emp);
    		context.Departments.Add(dept);
    		context.SaveChanges();
    	}
    	catch(Exception ex)
    	{ }
    }

    In above code, new line is added: context.Database.Initialize(force: false);

    check this site for details:

    https://msdn.microsoft.com/en-us/library/jj691402(v=vs.113).aspx

    Wednesday, March 8, 2017 5:33 PM
  • User753101303 posted

    Hi,

    My first thought would be to move the Database initializer outside of the constructor (before creating the context for the first time from you main load page) and see what happens.

    Wednesday, March 8, 2017 5:51 PM
  • User1397563414 posted

    Hi PranaySingireddy,
    Try to use the methods which is raju dasa and PatriceSc provide, and see if it will work.

    I guess it is because the connection is not avaliable. So, the dbcontext is creating the database and inserting data to table at the same time.

    Try to check the connection string, and see if it is correct.

    Get more help from
    http://stackoverflow.com/questions/9750115/the-context-cannot-be-used-while-the-model-is-being-created 

    Hope this will help.

    Best regards,
    JiyaoLee

    Thursday, March 9, 2017 2:21 AM