Entity Framework 4 with an existing domain model

I am currently reviewing the transition from free nHibernate to ADO.Net Entity Framework 4.
I have a project containing a domain model (pocos) that I used for nHibernate mappings. Ive read on blogs that you can use my existing domain model with EF4, but ive did not see any examples of this. I have seen examples of generating T4 code with EF4, but havent come across an example that shows how to use existing domain model objects with EF4. Im newby with EF4 and would like to see some examples of how to do this.

Thanks Aiyaz

+4
source share
1 answer

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 entities in your entity data model with the same names as your domain classes. Object properties must also have the same names and types as in domain classes.
  • Create a class inherited from ObjectContext to open objects (usually in the same project as the .edmx file)
  • In this class, create a property of type ObjectSet<TEntity> for each of your entities

Code example:

 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; } } 

What about this ...

Important note: if you use automatic proxy creation to track changes ( ContextOptions.ProxyCreationEnabled , which is true by default), the properties of your domain classes should be virtual >. This is necessary because proxies created by EF 4.0 override them to implement change tracking.

If you do not want to use automatic proxy creation, you will need to track the changes yourself. See this MSDN page for more details.

+6
source

All Articles