0

I have to create some new entities in a new or existing database using Entity Framework that will need to interact with some legacy tables and I'm wondering what the best approach is here. I was hoping to use Code First with migrations.

For example, say I have an existing populated Person table and I need to create a Animal table that will contain a PersonId foreign key to reference the existing people.

As far as I can tell these are my options:

  • Create a new DBContext (for a new DB) with an DBSet<Animal>, using code first migrations and POCO entity classes. Ran into problems with setting up the foreign key pointing to another DB.
  • Create a new DBContext (targeting the existing DB) with DBSet<Animal> and create some kind of POCO wrappers around the existing table. I'm not sure if this is possible - I tried something like but when applying the migration EF tried to create the Person table. I assumed this would map to the existing table instead of creating a new one:

    [Table("Person")]
    public class Person { 
    
  • Use Database first with the existing DB and create the tables in the existing DB but then I lose out on using POCO and migrations with my new entites.

Are there any better options that I'm missing or should I go ahead with using Database first?

3
  • Would code first from Database or Code First Migrations with an existing database work for you? Commented Sep 9, 2016 at 15:12
  • You can generally make code-first work with an existing db, so i wouldn't switch to db-first just for this reason. You just need to dig into the modelling conventions that EF applies (often in the OnModelCreating event), along with some selective manual edits of the migration scripts themselves to accommodate what already exists. You can dig as deep as you need to into EF, and people do this regularly to make it work with a wide variety of circumstances. Commented Sep 9, 2016 at 15:13
  • I didn't know that code first from Database existed - that looks ideal Commented Sep 9, 2016 at 15:27

1 Answer 1

3

You can use EntityFramework Reverse POCO Code First Generator.

Reverse engineers an existing database and generates Entity Framework Code First Poco classes, Configuration mappings and DbContext. This generator was designed to be customisable from the very beginning, and not fixed and rigid like other generators. Go and play with the settings in the .tt file, that's what it's there for.

Here is the link : EntityFramework Reverse POCO Generator

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.