Entity Framework 4.1Code First Connection to Sql Server 2005

I am trying to use Entity Framework 4.1 RC with an instance of SQL Server 2005. I created an empty database and I would like to save my POCO objects. My POCO looks like this:

public class Cart { public Cart() { this.CartId = Guid.NewGuid(); } public Guid CartId { get; set; } public decimal TotalCost { get; set; } public decimal SubTotalCost { get; set; } public decimal Tax { get; set; } public decimal EstimatedShippingCost { get; set; } } 

My CartContext:

 public class CartContext : DbContext { public DbSet<Cart> Carts { get; set; } public DbSet<Attribute> Attributes { get; set; } public DbSet<AttributeItem> AttributeItems { get; set; } } 

I have a connection string:

 <add name="CartContext" connectionString="Server=myserver.mynetwork.net;User ID=MyUser;Pwd=mypassword;Initial Catalog=ExistingDb" providerName="System.Data.SqlClient" \> 

When I try to add an object to the context and save it, I get:

System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating records. See Internal Exception for Details. ---> System.Data.UpdateException: error updating records. See Internal Exception for more details. ---> System.Data.SqlClient.SqlException: Invalid object name 'dbo.Carts'.

If I profile the database, I see the user connecting, searching for the database in sys.tables triggers this query:

 SELECT TOP (1) [Extent1].[Id] AS [Id], [Extent1].[ModelHash] AS [ModelHash] FROM [dbo].[EdmMetadata] AS [Extent1] ORDER BY [Extent1].[Id] DESC 

Then try to insert my cart object. He never tries to create the "Carts" table. I assume that something is wrong with the connection string, but I cannot find examples anywhere on how to do this.

+6
entity-framework ef-code-first
source share
1 answer

DbContext will not create a table just because it does not exist. After you use an existing database, you must also manually create tables or create a custom initializer. Initializers can delete the database by default and create new ones with all the necessary tables.

You can, for example, call:

 context.Database.Delete(); context.Database.Create(); 

Or:

 context.Database.CreateIfNotExists(); 

Or:

 Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MyContext>()); // You don't need to call this. Initialization takes place anyway if context // needs it but you can enforce initialization for example in the application // startup instead of before the first database operation context.Database.Initialize(true); 
+8
source share

All Articles