0

I'm working on a project and have had a terrible time getting my database to populate data from my SampleData.cs code. I saw another article explain on how to create the database, which worked, but the database still won't populate with code.

Here is my Global.asax page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Data.Entity;
using RickFinalProject.Models;

namespace RickFinalProject
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode, 
// visit http://go.microsoft.com/?LinkId=9394801

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        Database.SetInitializer(new SampleData());


        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        AuthConfig.RegisterAuth();
    }
}
}

My Web.Config page

<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<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=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-RickFinalProject-20140419005807;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-RickFinalProject-20140419005807.mdf"
  providerName="System.Data.SqlClient" />
<add name="RickFinalProjectDBContext" connectionString="Data Source=(localdb)\v11.0; Initial Catalog=RickFinalProjectDBContext-20140419010343; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|RickFinalProjectDBContext-20140419010343.mdf"
  providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<pages>
  <namespaces>
    <add namespace="System.Web.Helpers" />
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization" />
    <add namespace="System.Web.Routing" />
    <add namespace="System.Web.WebPages" />
  </namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers><remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" /><remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" /><remove name="ExtensionlessUrlHandler-Integrated-4.0" /><add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" /><add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" /><add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /></handlers></system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="DotNetOpenAuth.Core" publicKeyToken="2780ccd10d57b246" />
    <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.1.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="DotNetOpenAuth.AspNet" publicKeyToken="2780ccd10d57b246" />
    <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.1.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-1.3.0.0" newVersion="1.3.0.0" />
  </dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
</configuration>

My SampleData.cs page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace RickFinalProject.Models
{
//public class SampleData : CreateDatabaseIfNotExists<RickFinalProjectDBContext>
public class SampleData : DropCreateDatabaseIfModelChanges<RickFinalProjectDBContext>
{
    protected override void Seed(RickFinalProjectDBContext context)
    {

        var expansions = new List<Expansion>
        {
            new Expansion { ExpansionName = "Ravnica" },
            new Expansion { ExpansionName = "Mirrodin" },
            new Expansion { ExpansionName = "Saviors of Kamigawa" }
        };

        new List<Card>
        {
            new Card { CardName = "Platinum Angel", Expansion = expansions.Single(a => a.ExpansionName == "Mirrodin"), Rarity = "Rare", Color = "Colorless", Cost = 7, Type = "Artifact Creature",  Wording = "Flying, You can't lose the game and your opponents can't win the game." },
            new Card { CardName = "Char", Expansion = expansions.Single(a => a.ExpansionName == "Ravnica"), Rarity = "Rare", Color = "Red", Cost = 4, Type = "Instant",  Wording = "Char deals 4 damage to target creature or player and 2 damage to you." },
            new Card { CardName = "Twincast", Expansion = expansions.Single(a => a.ExpansionName == "Saviors of Kamigawa"), Rarity = "Rare", Color = "Blue", Cost = 2, Type = "Instant",  Wording = "Copy target instant or sorcery spell. You may choose new targets for that spell." }

        }.ForEach(a => context.Cards.Add(a));
    }
}
}

I'm really lost because it seems like this has worked on other projects I've seen and done. Any help will be much appreciated. Thank you.

Edit 1: There are no errors. The database simply isn't populating the data. I did a select * from Card; and it was empty. The SampleData.cs should add data to the database... right?

Jon Limjap
  • 94,284
  • 15
  • 101
  • 152
  • Could you at least show the error so we will be able to answer. –  Apr 19 '14 at 08:02
  • did you try updating database with verbose? –  Apr 19 '14 at 08:07
  • See edit. There is no error thrown, the database simply isn't populating data from the sampledata.cs page. – user3551168 Apr 19 '14 at 08:11
  • as stated by artm you need to do context.SaveChanges(); after adding something to the context, otherwise nothing will go through to the database. Just to clarify, a context is just tracking the models that you get, add, update or delete. – Joakim Apr 19 '14 at 09:19

1 Answers1

0

Sorry can't comment,

  1. Are you sure you are checking the correct DB for the changes? You have 2 connection strings.

  2. Put a SaveChanges at the end of Seed and see if you get anything useful.

  3. Debug Seed

    if (System.Diagnostics.Debugger.IsAttached == false) System.Diagnostics.Debugger.Launch();

from Debug code-first Entity Framework migration codes

Community
  • 1
  • 1
artm
  • 8,554
  • 3
  • 26
  • 43
  • Thanks for your suggestions. Unfortunately adding context.SaveChanges(); at the end of the Seed function didn't make any difference. – user3551168 Apr 19 '14 at 10:52