Entity Framework with existing database



I'm looking to implement entity framework version 4.3.1 in my existing project which don't follow this EF.The database is already developed and is currently used applying ado.net.In this case how do I start with to work on EF, is it Database First,Code first.

4/11/2013 2:47:11 PM

Accepted Answer

Even when a database already exists I still use the Code First approach, mapping the tables using annotations, because the domain is way more organized than on the EDMX file. If there are many tables the visual EDMX can become really useless since the design will be overcrowded with data and connections all over the place.

In two steps you can begin with this approach:

1) Create a domain model class, Customer for example, and map it to your table using data annotations:

public class Customer
    public int CustomerId { get; set; }
    public string Name { get; set; }
    // Add other properties below

2) Create a context class deriving from DbContext and set DbSet<T> properties for each model, we have only one in our case so:

public class MyApplicationContext: DbContext
    public MyApplicationContext() : base("name=ConnectionStringName") { }

    public DbSet<Customer> Customers { get; set; }

Now anywhere in your code can instantiate the derived DbContext class and make queries using Linq:

var _db = new MyApplicationContext();
var customer = _db.Customers.Where(c => c.CustomerId == 37).FirstOrDefault();

Don't forget to add a reference to EntityFramework assembly using NuGet.

Good Luck.

4/11/2013 3:06:56 PM

Popular Answer

Since your database already exists the obvious choice is Database first. If the database is designed with common sense it (mostly) works great.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow