locked
EF Code-First not generating database in ASP.NET application RRS feed

  • Question

  • I have created an ASP.NET application which is to be used as a service. I followed a tutorial at www.entityframeworktutorial.net to apply a code-first approach to generating a database since I had already manually written some of my model classes. Below is my context class "ShopContext"

    public class ShopContext : DbContext
        {
            public ShopContext() : base("iShopDb")
            {
                Database.SetInitializer<ShopContext>
                (new iShopDbInitializer());
            }
    
            public DbSet<OrderSummaryTypeDb> OrderSummaryTypeDbSet { get; set; }
    
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                modelBuilder.Configurations.Add(new OrderSummaryTypeDbConfiguration());
            }
        }

    As observed I set up a name for the database "iShopDb" in base parameter (I also tried passing the connectionstring from web.config but didn't work, more detail on this further down). I am only working with one class for now called "OrderSummaryTypeDb" just to get this working. Below is my iShopDbInitializer class:

    public class iShopDbInitializer : System.Data.Entity.DropCreateDatabaseAlways<ShopContext>
        {
            protected override void Seed(ShopContext context)
            {
                List<OrderSummaryTypeDb> orders = new List<OrderSummaryTypeDb>
                {
                    new OrderSummaryTypeDb
                    {
                        CustomerId = "004429",
                        VehicleId = "6005",
                        OrderId = "00022868",
                        OrderNumber = "024951",
                        FullName = "Carpenter, George",
                        Hat = "042",
                        Location = "side lot",
                        LicensePlate = "005TMZ",
                        YearMakeModel = "2005 Chevrolet Aveor",
                        Color = "Blue",
                        //OrderType = iShopMessages.OrderTypeType.RepairOrder,
                        EquipmentIdentifier = "28940397",
                        EquipmentModelNumber = "WA400",
                        //EquipmentState = iShopMessages.EquipmentStateType.Ready
                    },
    
                    new OrderSummaryTypeDb
                    {
                        CustomerId = "111222",
                        VehicleId = "3005",
                        OrderId = "00099881",
                        OrderNumber = "023232",
                        FullName = "Sabogal, Gonzalo",
                        Hat = "043",
                        Location = "Hunter garage",
                        LicensePlate = "123ABC",
                        YearMakeModel = "2010 BMW 335i",
                        Color = "Blue",
                        //OrderType = iShopMessages.OrderTypeType.RepairOrder,
                        EquipmentIdentifier = "88877722",
                        EquipmentModelNumber = "WA500",
                        //EquipmentState = iShopMessages.EquipmentStateType.Ready
                    }
                };
    
                foreach (var orderSummaryTypeDb in orders)
                {
                    context.OrderSummaryTypeDbSet.Add(orderSummaryTypeDb);
                }
    
                base.Seed(context);
            }
        }

    Based on the data I am seeding I am simply expecting a Db to be created with one table for my "OrderSummaryTypeDb" model and 2 instances (rows) with the information above.. 

    Now I will say that prior to doing all this I first generated a database manually, and also via an EDM-first approach, but these caused me some problems and I wasn't sure how to proceed, so then I deleted these EDM/Db files entirely and began from scratch with this code-first approach. However I think during that process my global web.config file was changed for me, here it is:

    <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>
      <system.web>
        <compilation debug="true" targetFramework="4.5" />
        <httpRuntime targetFramework="4.5" />
      </system.web>
      <system.serviceModel>
        <behaviors>
          <serviceBehaviors>
            <behavior name="">
              <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
              <serviceDebug includeExceptionDetailInFaults="false" />
            </behavior>
          </serviceBehaviors>
        </behaviors>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
      </system.serviceModel>
      <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>
      <connectionStrings><add name="OrderSummaryTypeDbContainer" connectionString="metadata=res://*/OrderSummaryTypeDb.csdl|res://*/OrderSummaryTypeDb.ssdl|res://*/OrderSummaryTypeDb.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\ShopDb.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /><add name="ShopDbEntities" connectionString="metadata=res://*/ShopEntityModel.csdl|res://*/ShopEntityModel.ssdl|res://*/ShopEntityModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\ShopDb.mdf;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" /></connectionStrings>
    </configuration>

    I searched some blogs around the web and I have tried passing the name within connectionStrings to my base parameter (it doesn't work). I also tried finding the so called "mssqllocaldb" everywhere thinking this may be the Db generated for me, just located somewhere else, but no luck in finding it.

    My application builds and runs fine. I tried posting a picture of what SQL server object explorer looks like after I run and refresh the explorer, but this site won't let me post pictures for now until I have more activity in these forums (this is my first post ever).

    But basically no iShopDb to be found anywhere on the explorer, except 2 local dbs named "(localdb)\ProjectsV12" and "(localDB)\v11.0". No iShopDb found when I expend these.

    Any help is appreciated thanks.

    Thursday, December 3, 2015 10:53 PM

Answers

  • Thanks for your response.

    connectionstring does not really matter as I am not trying to connect to an existing database, but to create a new one, what I am passing to the base parameter is just the name of the database I want.

    Anyhow, I was able to fix my issue thanks to a tutorial video on pluralsight.com showing how to use code first and migrations API to create the database.

    • Proposed as answer by Fred Bao Tuesday, December 29, 2015 8:10 AM
    • Marked as answer by Fred Bao Tuesday, December 29, 2015 8:10 AM
    Monday, December 7, 2015 5:35 PM

All replies

  • As an update. Based on the web.config file, I had to add a connection manually on the sql explorer to

    "(localdb)\mssqllocaldb" .However although I can connect to it, I still don't see my database being created there either. Not sure where I'm going wrong. I also tried commenting out the connectionStrings portion since I have a db initializer in-code which is set to dropcreatealways.

    Friday, December 4, 2015 10:38 PM
  • Hi Gonzalo,

    Seems your code snippet is not complete, I could not guess what  public ShopContext(connectstring) method looks like. Maybe you cloud post more information to make it clear.

    By the way, have you tried the code snippet from MSDN documentation? Could it run on my computer? Please try.

    https://code.msdn.microsoft.com/ASPNET-MVC-Application-b01a9fe8

    Regards,

    Saturday, December 5, 2015 1:10 AM
  • Thanks for your response.

    connectionstring does not really matter as I am not trying to connect to an existing database, but to create a new one, what I am passing to the base parameter is just the name of the database I want.

    Anyhow, I was able to fix my issue thanks to a tutorial video on pluralsight.com showing how to use code first and migrations API to create the database.

    • Proposed as answer by Fred Bao Tuesday, December 29, 2015 8:10 AM
    • Marked as answer by Fred Bao Tuesday, December 29, 2015 8:10 AM
    Monday, December 7, 2015 5:35 PM