English 中文(简体)
Custom Initialization Strategy for EF Code First that doesn t drop tables to add a column
原标题:

The latest EF Code First NuGet package comes with a custom implementation of IDatabaseInitializer called DontDropDbJustCreateTablesIfModelChanged. As the name implies, when a model change is detected, it will not drop and recreate the whole database, just drop and recreate the tables.

Say I have this model class:

public class User
{
    public string Username { get; set; }

    // This property is new; the model has changed!
    public string OpenID { get; set; }
}

How would one go about implementing an IDatabaseInitializer that doesn t drop any tables either. In this case, it would just add an OpenID column to the User table?

最佳回答

I think it is a matter of SQL. So for SQL Server you can write something like:

public class MyInitializer : IDatabaseInitializer<MyContext>
{
    public void InitializeDatabase(MyContext context)
    {
        context.Database.SqlCommand(
            @"
            IF NOT EXISTS (SELECT 1 FROM sys.columns AS col
                           INNER JOIN sys.tables AS tab ON tab.object_Id = col.object_Id
                           WHERE tab.Name =  User  AND col.Name =  OpenId )
            BEGIN
                ALTER TABLE dbo.User ADD OpenId INT; 
            END");
    }
}

But in the same way you can execute such script without adding it to your application which I think is much better approach.

问题回答

With the current version of Code First, you cannot simply amend your schema and preserve any data that you might have in your tables. If maintaining data, such as reference data / lookup tables is important with this release you can create your own Initializer and override the Seed method to populate your tables

public class MyDbInitializer : DropCreateDatabaseIfModelChanges<MyContext>
{
    protected override void Seed(MyContext context)
    {
        var countries = new List<Country>
        {
            new Country {Id=1, Name="United Kingdom"},
            new Country{Id=2, Name="Ireland"}
        };

        countries.ForEach(c => context.Countries.Add(c));
    }
}

And then use this in your Application_Start:

Database.SetInitializer<MyContext>(new MyDbInitializer());

I believe that this is being addressed currently by the EF Team, but wasn t ready for release at the time the Code First drop came out. You can see a preview here: Code First Migrations





相关问题
Entity Framework with MySQL connector in c#

I have been trying to get the Entity Framework to work in my web application using MySQL. It works fine on my local pc, but doesn t work when I put it on the server. Since the server is a shared ...

How Do I Create And Update A Many To Many Relationship With EF

I am using the Entity Framework with SQL Server. I have a many to many relationship between 2 tables. I have created a join table with just the primary key fields of the 2 tables. In the designer, the ...

Entity Framework with File-Based Database

I am in the process of developing a desktop application that needs a database. The application is currently targeted to SQL Express 2005 and works wonderfully. However, I m not crazy about having ...

Linq to enties, insert foreign keys

I am using the ADO entity framework for the first time and am not sure of the best way of inserting db recored that contain foreign keys. this is the code that i am using, I would appreciate any ...

Entity Framework - Many to many question

I have a table called ASB and a table called PeopleInvolved. There is a junction table called PeopleInvolved_ASB which simply contains an ASBID and a PeopleInvolvedID column. The columns act as a ...

Post back complex object from client side

I m using ASP.NET MVC and Entity Framework. I m going to pass a complex entity to the client side and allow the user to modify it, and post it back to the controller. But I don t know how to do that ...

ADO.NET Entity Data Model are not precise enough

I run this code: var cos = from k in _db.klienci_do_trasy where k.klient_id == 5 select k; but the query send to database is: SELECT * FROM `klienci_do_trasy` LIMIT 0, 30 why is it for, there ...

热门标签