I am having some troubles connecting to my database in Entity Framework6, using Code First approach.

Instead of connecting to my local DB that gets created in the App_Data folder, I have set up my connection string to point to a empty Database (no tables) in SQL Server.

Here is my connection string:

<add name="LiquorContext" connectionString="Data Source=.; Initial Catalog=MVC_Code_First;User ID=sa; Password=*******;" providerName="System.Data.SqlClient" />

Whenever this line gets called in my ViewModel, I get the "System.ArgumentNullException: Value cannot be null. Parameter name: source" error:

var users = context.Users.ToList();

Could this possibly be that my Seed method is not being called, as I have placed a breakpoint there, but never gets reached?

Here is my Context class:

public class LiquorContext : DbContext
{
    public LiquorContext()
        : base("LiquorContext")
    {

    }

    public DbSet<ExampleUser> Users;

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention>();
    }
}

Here is my ContextInitializer:

public class LiquorContextInitializer : DropCreateDatabaseIfModelChanges<LiquorContext>
{
    protected override void Seed(LiquorContext context)
    {
        var users = new List<ExampleUser>()
        {
            new ExampleUser { Name="a", Surname="b"},
            new ExampleUser { Name="c", Surname="d"},
            new ExampleUser { Name="e", Surname="f"},
            new ExampleUser { Name="g", Surname="h"}
        };
        foreach (var user in users)
        {
            context.Users.Add(user);
        }
        context.SaveChanges();
    }
}

Here I call the Initializer in the Global.asax file:

protected void Application_Start()
    {
        Database.SetInitializer<LiquorContext>(new LiquorContextInitializer());
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

Any help would be appreciated. Thanks

Related posts

Recent Viewed