Search code examples
c#linq-to-entities

Linq-to-EF starting with database first


I'm coming the Linq-to-SQL world and I want to create a new linq-to-EF6 datacontext.

With Linq-to-SQL, you just create a new data model that outputs a designer onto which you drag and drop tables from an existing database. Here, I tried creating a file with Add -> EF 6.x DbContext Generator and I'm not getting a designer where I can drag and drop tables from the database; instead I'm getting 2 .tt files that are black. I've looked online and most tutorials are about code-first approach but in my case I already have the database.

What do I need to do to create the datacontext that I can use in Linq-to-EF?


Solution

    1. Add a "ADO.Net Entity Data Model" to your project.
    2. Create your model from scratch or from an existing database
    3. Add a "EF 6.x DbContext Generator" to your project.
    4. Edit the Model.tt file and replace "$edmxInputFile$" by the name of your EDMX file
    5. Edit the Model.Context.tt file and replace "$edmxInputFile$" by the name of your EDMX file

    The *.tt files are T4 templates, which are basically code that generate code. Their role here is to parse the EDMX file for you, and generate the associated entities (Model.tt) and DbContext (Model.Context.tt).

    To execute a T4 template (for example to update the generated DbContext/entities once you've modified your edmx), right click on the *.tt file and click on "run custom tool".