CJ7
CJ7

Reputation: 23295

How to use legacy classes with EF Code First?

I have a large number of legacy classes written in C#, which I would like to use with EF Code First.

What needs to be done to these classes to make them usable for EF Code First?

Upvotes: 2

Views: 155

Answers (1)

Chris
Chris

Reputation: 6325

IF your classes are POCO entity classes, its really quite easy to use those with entity frameworks code first. FK relationships would need to be definied in the entities which have those types of relationships. Example:

public virtual ICollection<CmsCategoryType> CategoryTypes { get; set; } 

Secondly, you would need to make a DBcontext class which will actually wire everything up for you. Example:

public class CampaignContext :  DbContext
{
    public DbSet<CmsContent> Contents { get; set; }
    public DbSet<CmsCategoryType> CategoryTypes { get; set; }
}

Having a connection string pre-defined is also a good idea. Example:

<add name="CampaignContext" connectionString="Data Source=localhost\SQLEXPRESS;
                            Initial Catalog=Campaigns;
                            Integrated Security=True" 
                            providerName="System.Data.SqlClient"/>

Now when you run the application for the first time, entity frameworks code first will go out to the sql server specified in the connection string create the database with the pre definied name, take your entity classes and create tables with primary and foreign key relationships and generally wire everything up for you through the dbcontext.

Things to note, the connection string name and your dbcontext should have the same name, by convention the dbcontext looks for matching names. Also you might be missing some releationships that you think you should have. Once again, that's the virtual ICollections that need to be set going back and forth between related entities.

Hope this helps some, and good luck on your project.

Upvotes: 1

Related Questions