Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 4.1Code First connecting to Sql Server 2005

I'm trying to use the Entity Framework 4.1 RC with a SQL Server 2005 instance. I've created an empty database and I'd like to persist my POCO objects to it. My POCO looks like:

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 is:

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 and add an object to the context and save it I get:

System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Invalid object name 'dbo.Carts'.

If I profile the database I can see the user connect, look for the database in sys.tables run this query:

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

Then attempt to insert my cart object. It never tries to create the Carts table. I'm guessing there's something wrong with the connection string, but I can't find examples anywhere on how to do this.

like image 893
Chris Brent Avatar asked Mar 17 '11 22:03

Chris Brent


1 Answers

DbContext will not create table just because it doesn't exists. Once you are using existing database you must also manually create tables or create custom initializer. Default initializers are only able to drop the database and create new one with all required 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); 
like image 157
Ladislav Mrnka Avatar answered Oct 14 '22 10:10

Ladislav Mrnka