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
In my LiquorContext class, I had the DbSet<> as follow:
public DbSet<ExampleUser> Users;
By adding the { get; set; } as follow, it works:
public DbSet<ExampleUser> Users { get; set; }
Without more information is hard to say. Did you set a database initializer in the constructor for your context? This might help:
http://www.codeproject.com/Articles/794187/Various-Strategies-to-Initialize-Database-in-Entit
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.