views:

235

answers:

1

Hi,

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 mappings. Ive read in blogs that it is possible to use my existing domain model with EF4 but ive seen no examples of it. Ive seen examples of T4 code generation with EF4 but havent come accross an example which shows how to use existing domain model objects with EF4. Im a newby with EF4 and would like to see some samples on how to get this done.

Thanks Aiyaz

+2  A: 

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

Thomas Levesque
Thanks for that, Ive got it now. took a while to get past the T4 template generation though.
ace

related questions