I am using EF 4.1 and have created a repository using DBContext etc. Connection string set to point to a SQL Server 2008 R2 Dev edition.
When I run a console app that calls my gateway which in turn adds an entity and saves, an exception is thrown saying it can't find the table. When I look at my db, there is a database created but there are no tables created automatically except EmdMetadata.
Am I missing something?
Mark
Versioning databases is hard, but with code first and code first migrations, it's much more effective. Because your database schema is fully based on your code models, by version controlling your source code you're helping to version your database.
The Entity framework will not support to have a table without primary key, but we can overcome this issue by accessing the table with additional column via a view and marking the new column as Primary in entity framework. Entity Framework requires primary keys for entities.
To set the auto drop and create you would do something like this...
public class MyDbContext : DbContext
{
public IDbSet<Foo> Foos { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer(new MyDbContextInitializer());
base.OnModelCreating(modelBuilder);
}
}
public class MyDbContextInitializer : DropCreateDatabaseIfModelChanges<MyDbContext>
{
protected override void Seed(MyDbContext dbContext)
{
// seed data
base.Seed(dbContext);
}
}
You can create the tables yourself - the easiest way is:
IObjectContextAdapter adapter = (IObjectContextAdapter)context;
string script = adapter.ObjectContext.CreateDatabaseScript();
context.Database.ExecuteSqlCommand(script);
Where context is my EF 4.1 database context. Prior to this code I drop all the tables (from the last time I created the db), and after this I seed it with data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With