Dela via


EF 4.1 Model & Database First Walkthrough

 


The information in this post is out of date.

Visit msdn.com/data/ef for the latest information on current and past releases of EF.

For Model First see https://msdn.com/data/jj205424

For Database First see https://msdn.com/data/jj206878


 

Entity Framework 4.1 RTW is now available and is the first fully-supported go-live release of the DbContext API.

This post will provide an introduction to Model First and Database First development with the DbContext API, using the Entity Data Model Designer in Visual Studio.

You will need to have Visual Studio 2010 installed to complete this walkthrough.

 

1. Install EF 4.1

If you haven’t already done so then you need to install Entity Framework 4.1.

 

2. Create the Application

To keep things simple we’re going to build up a basic console application that uses the DbContext to perform data access:

  • Open Visual Studio 2010
  • File -> New -> Project…
  • Select “Windows” from the left menu and “Console Application”
  • Enter “ModelFirstSample” as the name
  • Select “OK”

 

3. Create the Model

Let’s go ahead and add an Entity Data Model to our project;

  • Project –> Add New Item…
  • Select ‘Data’ from the left menu
  • Select ‘ADO.NET Entity Data Model’ from the list of available items
  • Name the model ‘PersonModel.edmx’
  • Click ‘Add’

We are going to use Model First for this walkthrough but if you are mapping to an existing database you would now select ‘Generate from database’, follow the prompts and then skip to step 4.

  • Select ‘Empty model’
  • Click ‘Finish’

Let’s add a Person entity to our model:

  • On the design surface; Right Click –> Add –> Entity
  • Name the entity ‘Person’
  • Click ‘OK’
  • On the Person entity; Right Click –> Add –> Scalar Property
  • Name the property ‘Full Name’

image

Now that we’ve defined the model we can generate a database schema to store our data:

  • On the design surface; Right Click –> Generate Database from Model
  • Click ‘New Connection…’
  • Specify the details of the database you wish to create
  • Click ‘OK’
  • If prompted to create the database; click ‘Yes’
  • Click ‘Next’ then ‘Finish’
  • On the generated script; Right Click –> Execute SQL…
  • Specify your database server and click ‘Connect’

 

4. Swap to DbContext Code Generation

The PersonModel is currently generating a derived ObjectContext and entity classes that derive from EntityObject, we want to make use of the simplified DbContext API:

  • On the design surface; Right Click –> Add Code Generation Item…
  • Select ‘Code’ from the left menu
  • Select ‘ADO.NET DbContext Generator
  • Name the item ‘PersonModel.tt’
  • Click ‘Add’

You’ll notice that two items are added to your project:

  • PersonModel.tt
    This template generates very simple POCO classes for each entity in your model
  • PersonModel.Context.tt
    This template generates a derived DbContext to use for querying and persisting data

 

5. Read & Write Data

Time to access some data, I’m padding out the Main method in Program.cs file as follows;

 class Program
{
    static void Main(string[] args)
    {
        using (var db = new PersonModelContainer())
        {
            // Save some data
            db.People.Add(new Person { FullName = "Bob" });
            db.People.Add(new Person { FullName = "Ted" });
            db.People.Add(new Person { FullName = "Jane" });
            db.SaveChanges();

            // Use LINQ to access data
            var people = from p in db.People
                            orderby p.FullName
                            select p;

            Console.WriteLine("All People:");
            foreach (var person in people)
            {
                Console.WriteLine("- {0}", person.FullName);
            }

            // Change someones name
            db.People.First().FullName = "Janet";
            db.SaveChanges();
        }

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }
}

 

Summary

In this walkthrough we looked at Model First development using the new DbContext API in EF 4.1. We looked at building a model, generating a database, swapping to DbContext code generation and then saving and querying data.

Feedback & Support

This is a fully supported release. The ADO.NET Entity Framework Forum can be used for questions relating to this release. Further information about getting technical support can be found at the Microsoft Support website.

Rowan Miller

Program Manager

ADO.NET Entity Framework

Comments

  • Anonymous
    March 15, 2011
    很期待你们的4.1版!!

  • Anonymous
    March 16, 2011
    There is no "ADO.NET DbContext Generator". What should I do?

  • Anonymous
    March 16, 2011
    Best wishes!

  • Anonymous
    March 22, 2011
    Is this going to work with EF 4.0 providers like the new Oracle support for EF, or will they need to change stuff to support 4.1?

  • Anonymous
    March 23, 2011
    The comment has been removed

  • Anonymous
    March 25, 2011
    What if I wanted to generate a database for the database stored in App_Data? It doesn't seem to be able to connect, nor can it be opened with SSMS 2008.

  • Anonymous
    March 30, 2011
    For those wondering where the "ADO.NET DbContext Generator" is, you have to install the full package for EF4.1 (ie, download it from the site).  I'm assuming you used NuGet which does not include several useful tools.  (as of March 30, 2011)

  • Anonymous
    March 30, 2011
    Hmm, strange, I get nothing returned from the DB table. I am using this example i.e. I have created a Console application to test out the EntityFramework Database First stuff. The only difference is that I have seperated the Model stuff into a seperated Class Library project. When I try returning some data using the above example nothing is returned from the database (even though I can see data in there if I run an SQL query). Any ideas?   I am on a Windows XP SP3 32bit PC with Visual Studio 2010 Premium MSDN. Cheers, T

  • Anonymous
    March 31, 2011
    Okay found something odd (or I am missing the point). I can't use Database First in a Class Library (or I am missing references that are not obvious?).  I had a seperate library where I was planning to store my data centric stuff but when I reference this library inside a something like a WPF application I get all kinds of problems. When I placed everything inside the application (the Model, templates etc) it worked first time. So I am guessing Code First is the one geared towards libraries?  I guess I will need to test this in anger

  • Anonymous
    April 20, 2011
    Does anyone know if there are any disadvantages to doing it this way versus the original way if you are doing database first development? I'm pretty happy with the way things worked before, but, I'm interested in using the new simplified API if it's better. I'm just wondering if there are any gotchas with the new method. Are there any reasons not to use the new API instead?

  • Anonymous
    May 02, 2011
    I was fooled by this, it said database first not model first. Please fix the title. Thank you. /Rolf Sursomfansson

  • Anonymous
    May 20, 2011
    If I install the full package to get the DbContext generator, can I still use NuGet to install it into my project so that I keep the libraries together? I'm using TFS so I like the way NuGet adds the packages to the solution and to source control.

  • Anonymous
    June 09, 2011
    I was fooled as well, this isn't database first

  • Anonymous
    June 15, 2011
    Does your model have to follow conventions to do this? Or can i have my PK be PersonID?

  • Anonymous
    June 30, 2011
    Roffe and John, this does cover Database First if you read the following sentence carefully from step 3: > We are going to use Model First for this walkthrough but if you are mapping to an existing database you would now select 'Generate from Database,' follow the prompts and then skip to step 4. That's pretty much the main difference between Model First and Database First

  • Anonymous
    July 11, 2011
    Will this work if there is a inheritance between the models ??

  • Anonymous
    August 04, 2011
    Questions:

  1. After we have generated DbContext and POCO template (*.tt) classes, can we bypass DbContext API and use EDM API, if we need it?
  2.  DbContext and POCO template (*.tt) files are generated and are in sync with EDM. How can I now make changes to POCO template classes (for example decorate them with attributes for validation, add methods, etc), or make changes to DbContext template class (for example implementing method OnModelCreating with Fluenti API)? Is it thru "partial" classes or something else?
  3. As I can notice  DbContext Generator generates only classes but not relationships and constraints. Does it mean that relationships are maintained just in EDM?
  • Anonymous
    October 08, 2011
    Agreed... i also visited this looking at the title "Database first".. For most of the applications, I believe database is the first thing that gets developed (and should ideally!!!) so I am not much impressed with Model-first approach.. however, anyone has any idea about where I can find more information about database-first approach in EF 4 or 4.1? Thanks

  • Anonymous
    October 23, 2011
    Nirman:  I second that. MS appears totally uninterested in developing real world, quality EF tutorials that address database first (I mean a real world example that many related tables (at least 5-8 such tables).

  • Anonymous
    November 09, 2011
    @Nirman, it's a design decision, only in database-centric development the database is the first thing to emerge, Code/Model First is best used when you start off designing the application from the model and want to nail the persistent storage last.

  • Anonymous
    December 12, 2011
    The comment has been removed

  • Anonymous
    May 26, 2012
    It doesn't seem to work. I double-checked everything as pre instruction, build this UserModels.dll. Step. 1 In the dll, App.Config file, edmx generated this connection string: (hit the 'test' button when making it, connects successfully, and generated the edmx of all the tables in 'UserDatabase') <?xml version="1.0" encoding="utf-8"?> <configuration>  <connectionStrings>    <add name="UserModelsContainer" connectionString="metadata=res:///UserModels.csdl|res:///UserModels.ssdl|res://*/UserModels.msl;provider=System.Data.SqlClient;provider connection string="data source=MyDesktopSQL2008;initial catalog=UserDatabase;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />  </connectionStrings> </configuration> Step 2. Then I made a test project: class UnitTetst1 .... TestMethod1().... using (var db = new UserModelsContainer()) {  int i = db.Users.Count(); // <---expecting '0' as it is a new db } Step 3. ---------PROBLEM HERE ----------------- Run the test. Then I get an error InvalidOperationException like this: "No connection string named 'UserModelsContainer' could be found in the application config file." Seems like DbContext doesn't know where to pick up the App.Config -> connectionStrings

  • Anonymous
    May 29, 2012
    @Tom - You will need to move the App.config from the class library into the project that will be executing. You'll need a copy in each project that executes, so that includes one in your application and one in your test project.

  • Anonymous
    May 29, 2012
    I'm running EF 4.3.1.  This walkthrough worked for me, except EF 4.3.1 apparently doesn't  come with ADO.NET DbContext Generator . Thank you to Jeeshenlee above for showing how to get it. Why would I want to maintain a bunch of .tt files when I can tweak the EDMX file created in the demo here?  I changed the code generation strategy to default (instead of none) and  excluded all the .tt files from the project.   db.People.Add(new Person { FullName ="Bob" }); changes to db.AddToPeople(new Person { FullName ="Bob" }); Adding another table with a foreign key relationship would be useful since I've never heard of an application using a single table.

  • Anonymous
    May 30, 2012
    @Jules.Bartow - Here is an updated walkthrough that shows how to do Model/Database First with EF 4.2 onwards - blogs.msdn.com/.../ef-4-2-model-amp-database-first-walkthrough.aspx You have the option of using the default code generation or swapping to DbContext, which has a much simpler API surface. Currently you need to add the tt files to work with DbContext, the files just sit in your project though and you don't need to do anything to maintain them. We're currently working on swapping the default code generation to be DbContext (rather than ObjectContext) for the final release of Visual Studio 11. Hope this helps!

  • Anonymous
    July 28, 2012
    I am using this approach.  I figured it out before I found this post. I need help setting up unit tests.  I use Moq. I learned that MS published public interfaces for the DbContext entourage, which makes it easy (possible) to mock. blogs.msdn.com/.../productivity-improvements-for-the-entity-framework.aspx But that is just a baby step.  How to keep going and create really good unit tests that do not need a database? Mock<IPosManContext> posManContext; posManContext.Object.Set(typeof(note_template)); posManContext.Object.note_template.Add(    new note_template()    {        note_template_id = 1,        act_flag = "Y",        desc_text = "Monday Monday",        last_update_dtm = now,        last_update_user_id = "hsimpson",    }); But I get an error that the DbSet is null. Microsoft needs to provide a good example of what to do for unit test using mocking. They went half the way by providing public interfaces for mocking, but I still need more help.

  • Anonymous
    July 30, 2012
    @Joe Kahl – This post shows how to build fakes based on the interfaces - romiller.com/.../testing-with-a-fake-dbcontext It doesn’t use a mocking framework but the same principles apply. I agree that a post on how to use a mocking framework with DbContext is a great idea, I’m adding an item to our backlog to produce one.

  • Anonymous
    October 14, 2012
    Real good walkthrough and explainations.  Thanks very much.

  • Anonymous
    October 07, 2015
    How to display the particular data from datase using entity framework.

  • Anonymous
    December 10, 2015
    what about windows form  app data first??????