Entity Framework 4 with Existing Domain Model

前端 未结 1 1508
后悔当初
后悔当初 2021-02-10 21:42

Im currently looking at migrating from fluent nHibernate to ADO.Net Entity Framework 4.
I have a project containing the domain model (pocos) which I was using for nHibernate

相关标签:
1条回答
  • 2021-02-10 22:30

    Quick walkthrough :

    • 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

    Sample 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...

    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.

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

    0 讨论(0)
提交回复
热议问题