Repository pattern with Entity framework

后端 未结 4 2101
我寻月下人不归
我寻月下人不归 2020-12-12 20:01

Repository pattern is used to abstract from particular database and object-relation-mapping technology(like EF) used. So I can easily replace (for example) my Entity framewo

4条回答
  •  误落风尘
    2020-12-12 20:21

    The entity classes created by EF's designer are there in your project, inside your "Model.Designer.cs". You can copy the code so that your entities remain on your project even if you remove your model or the references from EF. However, they are tightly coupled to EF, so you should strive for decoupling EF from your entity classes.

    Until now, you had T4 templates that could help you with the decoupling, but they still would require some changes to the chosen T4:

    • ADO.NET EntityObject Generator
    • ADO.NET POCO Entity Generator
    • ADO.NET Self-Tracking Entity Generator

    EF4.1 brings a simplified API, DbContext, that improves your experience with EF when you want to decouple entity classes. With EF4.1 you get 3 approaches:

    • Code First
      • you create the classes and EF creates the DB as it should be
      • classes won't go away when you remove references to EF
      • you won't have any designer
    • Database First
      • if you already have a database, a model will be created for you on the designer
      • you can create your entity classes with the new T4 template DbContext Generator
    • Model First
      • as you already do right now, you create your model in the designer
      • you can create entity classes with DbContext Generator

    Now, answering your question:

    How do I remove this dependency ?

    1. Install EF4.1
    2. Create your model (using Model-first approach)
    3. Generate your database from your model
    4. Generate your entity classes with DbContext Generator

    See how you can do all this here: EF 4.1 Model & Database First Walkthrough.
    You should read the series in ADO.NET Team Blog Using DbContext in EF Feature CTP5 Part 1: Introduction and Model (EF4.1 was formerly known as EF Feature CTP5).
    You can get more details in my question: EF POCO code only VS EF POCO with Entity Data Model.

提交回复
热议问题