Thursday, May 23, 2013

How to access an Existing Database Using Entity Framework 5.0 Code-First

In my previous two articles we see how to use Entity Framework Code First and mvcscaffolding in asp.net mvc4. We didn't create any database into above articles. Database was created automatically from model class. But in this article I’ll explain how to use existing database in an EF code-first application. For this purpose we’ll make two small changes in any asp.net mvc code-first project.

1. Define connectionstring in web.config for existing database.

<connectionStrings>
    <add name="DonarConnectionString" connectionString="Data Source=MSSQLSERVER;initial catalog=BloodDonar;user id=sa;password=;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
  </connectionStrings>

2. In previous two articles we have created a database context class which is inherited from “DbContext”. Now we need a constructor for this class. Notice, in this constructor, that we call into the base constructor and pass it a string.  This is the connectionstring which is created in previous step. EF will use it during database connections.

        public InventoryContext(): base("name=DonarConnectionString")
        {
            Database.SetInitializer<MvcApplication2Context>(null);
        }

Here, we are setting the Initializer for the context to null with SetInitializer<>.  So, EF will not try to change any database initialization logic.

0 comments:

Post a Comment