Guilherme.Morais
Guilherme.Morais

Reputation: 53

How to change from Model-first to Code-First in Entity Framework

I had started a project with Model-First, with one existing base, now I need to change to code-first to change some specifics things in FK´s. So How I keep the classes and change to code-first? It´s even possible?

Upvotes: 0

Views: 152

Answers (2)

joelmdev
joelmdev

Reputation: 11773

Assuming you have already generated your database from your model, you can use the "Reverse Engineer Code First" feature of Entity Framework Power Tools. This will generate both your POCO model classes and Fluent API mapping classes for you.

Upvotes: 1

Timothy Shields
Timothy Shields

Reputation: 79461

I did this myself fairly recently. The expressive powers of Model-First and Code-First are identical. If you write your Code-First classes such that the property names and types match what you had in your Model-First types, the transition should be very easy.

For example, if you have a Model-First model Item with int ID key, string Name, and int ListID foreign key, with List List navigation property, you can make the Code-First class as follows.

class Item
{
    [Key]
    public int ID { get; set; }

    public string Name { get; set; }

    public int ListID { get; set; }

    [ForeignKey("ListID")]
    public virtual List List { get; set; }        
}

All of your old code that uses Item should likely remain working.

Upvotes: 1

Related Questions