Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 826
B Vidhya Avatar asked Apr 11 '13 14:04

B Vidhya


People also ask

Which approach will create Entity Framework from an existing database?

Entity Framework has a well-documented approach, called reverse engineering, to create the EF Entity Classes and DbContext from an existing database.

How do I add Entity Framework to an existing project?

Install Entity FrameworkRight click on your project name and select Manage NuGet Packages. Go to Browse and Select Entity Framework then click Install button to install Entity Framework on your project.

How do I connect to an existing database?

To connect to a database instanceRight-click the SQL Server node in SQL Server Object Explorer and select Add SQL Server. In the Connect to Server dialog box, enter the Server name of the server instance you want to connect to, your credentials, and click Connect.


2 Answers

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:

[Table("tbl_cust")]
public class Customer
{
    [Key]
    [Column("cust_id")]
    public int CustomerId { get; set; }
    [Column("cust_name")]
    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.

like image 114
Anderson Fortaleza Avatar answered Oct 19 '22 02:10

Anderson Fortaleza


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

like image 25
Z.D. Avatar answered Oct 19 '22 03:10

Z.D.