且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实体框架4与现有的域模型

更新时间:2023-11-20 21:51:28

快速演练:

  • 创建一个实体数据模型(的.edmx)在Visual Studio中,并清除EDMX文件的自定义工具属性设置为prevent code一代
  • 在使用相同的名称作为您的域名类的实体数据模型创建实体。实体的属性也应该有相同的名称和类型,在域类
  • 创建一个类从的ObjectContext 继承揭露实体(通常在同一个项目中的.edmx文件)
  • 在类中,创建类型的属性对象集< TEntity> 对于每次实体
  • Create an entity data model (.edmx) in Visual Studio, and clear the "custom tool" property of the edmx file to prevent code generation
  • Create the entities in your entity data model with the same names as your domain classes. The entity properties should also have the same names and types as in the domain classes
  • Create a class inherited from ObjectContext to expose the entities (typically in the same project as the .edmx file)
  • In that class, create a property of type ObjectSet<TEntity> for each of you entities

样品code:

public class SalesContext : ObjectContext
{
    public SalesContext(string connectionString, string defaultContainerName)
        : base(connectionString, defaultContainerName)
    {
        this.Customers = CreateObjectSet<Customer>();
        this.Products = CreateObjectSet<Product>();
        this.Orders = CreateObjectSet<Order>();
        this.OrderDetails = CreateObjectSet<OrderDetail>();
    }

    public ObjectSet<Customer> Customers { get; private set; }
    public ObjectSet<Product> Products { get; private set; }
    public ObjectSet<Order> Orders { get; private set; }
    public ObjectSet<OrderDetail> OrderDetails { get; private set; }
}

这就是它......

That's about it...

重要提示:如果您使用自动代理创建的变化跟踪( ContextOptions.ProxyCreationEnabled ,默认情况下是如此),属性你的域类的必须是虚。这是必要的,因为通过EF 4.0生成的代理将覆盖它们来实现更改跟踪。

Important notice : if you use the automatic proxy creation for change tracking (ContextOptions.ProxyCreationEnabled, which is true by default), the properties of your domain classes must be virtual. This is necessary because the proxies generated by EF 4.0 will override them to implement change tracking.

如果你不想使用自动代理的创建,您将需要处理的更改跟踪自己。请参见这个MSDN页细节

If you don't want to use automatic proxy creation, you will need to handle change tracking yourself. See this MSDN page for details