Map an existing entity class (POCO) in Entity Framework 4

Entity Framework stands for ADO.NET Entity Framework, ADO.NET is developed by Microsoft based on the ORM (Object / Relational Mapping) framework.

  Entity Framework's main features:

  1. supports multiple databases (Microsoft SQL Server, Oracle, and DB2);

  2. powerful mapping engine, can be a good support for stored procedures;

  3. Providing Visual Studio integrated tools for visualization;

  4. can be well integrated with the ASP.NET, WPF, WCF, WCF Data Services.

  For more profiles, please see: ADO.NET the Entity Framework At-A-the Glance

  Park in the new blog features short message development, we are ready to use Entity Framework 4, we first confronted with this question:

  Entity class already exists in the database, the field names and different attributes table with the class name in the database entity class table, the corresponding class. In other words we can not use the usual method in VS2010 to generate the entity classes and ObjectContext through the ADO.NET Entity Data Model (.edmx file).

  Note: This entity has a class called call POCO (Plain Old CLR Objects).

  Our solution is: in .edmx file manually configure mappings.

  Here are the steps:

  1. ADO.NET Entity Data Model, create a file .edmx VS2010, as shown below:

  The Entity Data Model Wizard operates in the database table selection window, enter the note existing namespace entity class Model Namespace in the input box, as shown below:

  3. Click Finish, to form the corresponding EntityType, as shown below:

  这里的EntityType是根据数据库中的表结构生成的,与实际的实体类是不一样的,表名与类名不一样,表的很多字段与类的属性不一样。

  下面我们配置映射的关键地方:

  4. 点击.edmx窗口点击空白处,在属性窗口中将Code Generation Strategy的属性设置为None(见下图),也就是不让VS2010自动生成实体类和对应的ObjectContext。

  5. 继续在.edmx窗口,选择实体类,点击右键选择Show in Model Browser,见下图:

  6. 进入Model Browser窗口,见下图:

  上图中,上面是实体类(这里是VS2010自动生成的,与数据库表是一一对应的),下面是表结构。

  修改映射就是在这里:在Entity Types中将类名改为实际的实体类名,将属性改为实际的属性,如下图:

  修改之后,映射就配置好了,.edmx文件中实体类图中也随之自动更改,见下图:

  7. .edmx文件实际就是一个xml文件,映射信息就存放在其中。在VS2010解决方案管理器中选择这个文件,右键Open With,选择用XML Editor打开,就可以看到.edmx文件的内容,如下图:

  8. 再写个继承自ObjectContext的类(见下图),工作就完成了。

转载于:https://www.cnblogs.com/zhangchenliang/archive/2012/12/03/2799114.html

Guess you like

Origin blog.csdn.net/weixin_34281477/article/details/93495287