locked
Entity Framework don't create database RRS feed

  • Question

  • User-54545710 posted

    Hi guys, i'm creating a database with entity framework, in an mvc asp.net application, using code first.

    I'm new to the argument so be patient... I've created the database for the first time and all seems to be right; but couse of i didn't create a DropCreateDatabaseIfModelChanges method to change the tables i decided to manually delete the database.

    The problem is that the database is not recreating!

    I've implemented the initializer and it is in a different class from the context...

    public class WidgetDbInitializer : DropCreateDatabaseIfModelChanges<WidgetDbContext>
    {
    }

    Setted it up in Global.asax.cs and forced to init that

    protected void Application_Start()
    {
    AreaRegistration.RegisterAllAreas();
    
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
    
    Database.SetInitializer<Portale.Models.WidgetDbContext>(new Portale.Models.WidgetDbInitializer());
    var _initer = new WidgetDbInitializer();
    
    using (var db = new WidgetDbContext())
    {
    _initer.Seedit(db);
    db.Database.Initialize(true);
    }
    }

    I've just the default connection string couse now i don't care about it...

    Please help me i've read tons of articles over the web and i can't get a solution...

    Monday, February 13, 2012 7:11 AM

Answers

  • User-54545710 posted

    Solved the problem -.-

        public class Widget
        {
            //This properties rapresent the primary key for entity framework
            [Key]
            public int WidgetID { get; set; }
            //Foreing key to the column where this widget is stored
            public virtual int ColumnID { get; set; }
            //The title of the widget
            public string Title { get; set; }
            //Controller of the Widget, this property may be used on the RenderAction call
            public string Controller { get; set; }
            //ActionMethod of the Widget, this property may be used on the RenderAction call
            public string ActionMethod { get; set; }
            //The Type of the Model, used on deserialization
            public Type ModelType { get; set; }
            //The context of the widget
            public string SerializedModel { get; set; }
    }

    The database just didn't accept the type "Type", all working fine as soon as i deleted that field... Feel free to blame me :\ , I just didn't look at it becouse it was working with the "Object" type, didn't expect it doesnt with Type.. Just for clarity; wich type of data cannot be used?

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, February 14, 2012 4:21 AM

All replies

  • User1492915735 posted

    Hi

     

    using (var db = new WidgetDbContext()) { _initer.Seedit(db); db.Database.Initialize(true); } }

     

    Try this

    WidgetDbContext db = new WidgetDbContext();

    db.table.Tolist(); //This will create database

    Monday, February 13, 2012 11:36 AM
  • User1985864055 posted

    The database isn't created until you try to read from it or write to it.

    Monday, February 13, 2012 12:51 PM
  • User-54545710 posted
    i've added your code but i get the same error i always get whenever i try to access the database; instaed of creating it i got error: ArgumentNullException , the parameter "key" can't be null. And i get this error every time i try access to database, adding element, selecting element; with elements not null
    Monday, February 13, 2012 1:08 PM
  • User1985864055 posted

    Can you try comparing your code to this tutorial to see what is different?

    http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

     

    Monday, February 13, 2012 1:17 PM
  • User-54545710 posted

    i've actually followed this for implementing mine code... the only different is in connection string; i use default... and in the seed method, i haven't overidden it at all, but the database should get online anyway i think, and it actually was before i deleted it manually 

    o.t. are u the Tom from the tutorial? that's great :)

    Monday, February 13, 2012 1:45 PM
  • User1985864055 posted

    Yes, I wrote the tutorial.  I would try giving the database a different name.  Sometimes you can run into problems with SQL Express when trying to create a database with the same name a second time.  There is a way to fix this using SQL Server Management Studio but it's generally easier to just use a different database name.

    Monday, February 13, 2012 1:49 PM
  • User1985864055 posted

    If the problem is the database name and you want to continue using the same name, here's a utility that's easier to install than SSMS:

    http://www.microsoft.com/download/en/details.aspx?DisplayLang=en&id=3990

     

    Monday, February 13, 2012 1:56 PM
  • User1492915735 posted

    ArgumentNullException , the parameter "key" can't be null. And i get this error every time i try access to database, adding element, selecting element; with elements not null       

     

    Apparently, I saw from you code. Are you forgot to add PK?

    Could you show us how did you add those entities and your model class?

    Monday, February 13, 2012 2:33 PM
  • User-54545710 posted

    i've renamed my dbcontext class to WidgetDatabaseContext instaed of WidgetDbcontext

    public class WidgetDatabaseContext : DbContext
        {
            public DbSet<WidgetContainer>   WidgetContainers    { get; set; }
            public DbSet<Column>            Columns             { get; set; }
            public DbSet<Widget>            Widgets             { get; set; }
    
    }

    and all the dbset in it have the pk as this

    public class Widget
        {
            //This properties rapresent the primary key for entity framework
            public int WidgetID { get; set; }
            //Foreing key to the column where this widget is stored
            public virtual int ColumnID { get; set; }
            //The title of the widget
            public string Title { get; set; }
    
    }

    renaming that class didn't have success; ill try in using that utility now...

    Monday, February 13, 2012 2:53 PM
  • User1492915735 posted

    Database.SetInitializer<Portale.Models.WidgetDbContext>(new Portale.Models.WidgetDbInitializer());

     var _initer = new WidgetDbInitializer();

       using (var db = new WidgetDbContext())

    {

     _initer.Seedit(db);

     db.Database.Initialize(true);

    }

    }

     

    Monday, February 13, 2012 3:01 PM
  • User1985864055 posted

    It would also be helpful to see the select/insert code that you get the error on.

    Monday, February 13, 2012 3:01 PM
  • User1492915735 posted

    You WidgetDbInitializer should similar look like this.

    public class SchoolInitializer : DropCreateDatabaseIfModelChanges<SchoolContext>

         {

             protected override void Seed(SchoolContext context)

             {

                 var students = new List<Student>

                 {

                     new Student { StudentID = 1, FirstMidName = "Weera", LastName = "Pong" },

                     new Student { StudentID = 2, FirstMidName = "Html", LastName = "JavaScript" },

                     new Student { StudentID = 3, FirstMidName = "Silverlight", LastName = "Ria Service" }

                 };

                students.ForEach(x => context.Student.Add(x));

                 context.SaveChanges();         }

         }

    Monday, February 13, 2012 3:03 PM
  • User1492915735 posted

    if you need to adding some data into DB. Your WidgetDbInitializer should similar below.

    public class SchoolInitializer : DropCreateDatabaseIfModelChanges<SchoolContext>

         {

             protected override void Seed(SchoolContext context)

             {

                 var students = new List<Student>             {

                     new Student { StudentID = 1, FirstMidName = "Weera", LastName = "Pong" },

                     new Student { StudentID = 2, FirstMidName = "Html", LastName = "JavaScript" },

                     new Student { StudentID = 3, FirstMidName = "Silverlight", LastName = "Ria Service" }

                 };

                students.ForEach(x => context.Student.Add(x));

                 context.SaveChanges();

             }

         }

    Monday, February 13, 2012 3:05 PM
  • User-54545710 posted

    As i said, i didn't override the seed method, just couse i don't need it at all, i've just code an init method ( it was named Seedit in the previus post ) to test the database, and called it in the application_start method:

    public class WidgetDbInitializer : DropCreateDatabaseIfModelChanges<WidgetDatabaseContext>
        {
    
            //INITIALIZE WITH TEST DATA
            public void Init(WidgetDatabaseContext context)
            {
                context.Database.CreateIfNotExists();
    
               // ... Initaliaze some test data ...            
    
                context.AddWidgetContainer(container);
                context.AddColumns(column);
                context.AddWidget(widget);
            }
        }

    Acutally i get the error every time i try to access the database:

    context.Database.CreateIfNotExists();

    this also give me the "key can't be null" error...

    The methods adding items to db look like this:

    //Add a new widget container entry in the widgetcontainers table
            public void AddWidget(Widget newWidget)
            {
                this.Widgets.Add(newWidget);
                this.SaveChanges();
            }
    Monday, February 13, 2012 3:12 PM
  • User-54545710 posted

    I'd like to share with you the stack trace till the error comes up:

    >Portale.DLL!Portale.Models.WidgetDbInitializer.Init(Portale.Models.WidgetDbCont‌ext context) Line 15 
    >Portale.DLL!Portale.MvcApplication.Application_Start() Line 47 + 0xd byte
    Monday, February 13, 2012 3:18 PM
  • User1492915735 posted

    There's tree way how to create. You should chose one of those.

    1. CreateIfNotExists

    2. DropCreateAlways

    3. DropCreateIfModelChanges

    That would be nice if you can post the links that you following.

    Monday, February 13, 2012 4:11 PM
  • User-54545710 posted

    As i posted before, im using CreateIfNotExist, read my previous post

    Monday, February 13, 2012 4:26 PM
  • User1492915735 posted

    Can you Repro your project then put it on SkyDrive so that we can test it?

    Confused:Embarassed

    Monday, February 13, 2012 4:41 PM
  • User-54545710 posted

    Listing databases with SSUTIL don't list the old database anymore, seems like it is deleted; but it don't have to be the problem anyway couse I've changed the name of the class...

    Can't upload my project, its so big and complicated, it will not help anyway...

    For clarity, this is the error i get:

    System.ArgumentNullException non è stata gestita dal codice utente
      Message=Il valore non può essere null.
    Nome parametro: key
      Source=mscorlib
      ParamName=key
      StackTrace:
           in System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
           in System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
           in System.Data.Entity.ModelConfiguration.Configuration.Mapping.SortedEntityTypeIndex.Add(EdmEntitySet entitySet, EdmEntityType entityType)
           in System.Data.Entity.ModelConfiguration.Configuration.Mapping.EntityMappingService.Analyze()
           in System.Data.Entity.ModelConfiguration.Configuration.Mapping.EntityMappingService.Configure()
           in System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.ConfigureEntityTypes(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
           in System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
           in System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
           in System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
           in System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
           in System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
           in System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
           in System.Data.Entity.Internal.InternalContext.Initialize()
           in System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
           in System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
           in System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
           in System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
           in System.Linq.Queryable.Join[TOuter,TInner,TKey,TResult](IQueryable`1 outer, IEnumerable`1 inner, Expression`1 outerKeySelector, Expression`1 innerKeySelector, Expression`1 resultSelector)
           in Portale.Controllers.WidgetContainerController.Index() in C:\Users\doompro\Documents\Visual Studio 2010\Projects\Portale\Portale\Controllers\WidgetContainerController.cs:riga 56
           in lambda_method(Closure , ControllerBase , Object[] )
           in System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
           in System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
           in System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
           in System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
           in System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
      InnerException: 
    

    I've also tryed to change from SQLExpress to SQLCompact as in Tom's tutorial with this connection string:

    <add name="WidgetDatabaseContext" connectionString="Data Source=|DataDirectory|WidgetDatabaseContext.sdf" providerName="System.Data.SqlServerCe.4.0"/>

    But nothing have changed...

    Tuesday, February 14, 2012 2:50 AM
  • User-54545710 posted

    Solved the problem -.-

        public class Widget
        {
            //This properties rapresent the primary key for entity framework
            [Key]
            public int WidgetID { get; set; }
            //Foreing key to the column where this widget is stored
            public virtual int ColumnID { get; set; }
            //The title of the widget
            public string Title { get; set; }
            //Controller of the Widget, this property may be used on the RenderAction call
            public string Controller { get; set; }
            //ActionMethod of the Widget, this property may be used on the RenderAction call
            public string ActionMethod { get; set; }
            //The Type of the Model, used on deserialization
            public Type ModelType { get; set; }
            //The context of the widget
            public string SerializedModel { get; set; }
    }

    The database just didn't accept the type "Type", all working fine as soon as i deleted that field... Feel free to blame me :\ , I just didn't look at it becouse it was working with the "Object" type, didn't expect it doesnt with Type.. Just for clarity; wich type of data cannot be used?

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, February 14, 2012 4:21 AM