views:

48

answers:

2

In some scenarios I need a "wide" version of an entity with many properties (say FullCustomer) while in other scenarios it's enough with a "narrow" version with few properties (say MiniCustomer), how could I map these two entities, FullCustomer and MiniCustomer, to the same Customer table in the database? Furthermore, I need to be able to query and update both entities.

Thanks in advance for any advice or pointers!

PD. I'm using VS2010 RC and EF 4

A: 

If you have a column that determines whether to treat the record as a FullCustomer or as MiniCustomer, then you can easily create a Table per Hierarchy inheritance model with FullCustomer inherited from MiniCustomer. Such approach is described in the Muhammad Mosa's blog post.
If you don't have this column you can update the model and database in order to add it.
However, there is an alternative approach. If the reason to have two entities for one table is the delay in the loading the numerous large properties in the FullCustomer object, than Table Splitting might be an option. Take a look at the Julie Lerman's blog post.
I would have noted that this problem is not present in ORMs like LINQ to SQL, due to deferred loading.

Devart
Hmm, Julie's post is very nice but it explains table splitting, that is: from the total of say 20 fields, put 15 in one entity and put the other 5 fields in another entity. Nice, but unfortunately what I want is to put the whole 20 fields in one entity and then a subset of 5 fields in another entity.
Edgar Sánchez
*Way* too much work. Plus you're encoding business rules (what gets edited when) into your schema.
Craig Stuntz
Hmm, you raise a very interesting poing Craig: I agree that "what gets edited when" is indeed a business rule so is up to the business logic to make this decision, OTOH I don't see anything wrong in having two (or three) versions of an entity and let the business logic pick the one most adequate for a given scenario (but I'm saying this in "just my 2 cents" mode :-)
Edgar Sánchez
A: 

For "efficiency", don't have two versions of the entity; just project onto "lite" POCOs:

var q = from e in Context.Entities
        select new LitePoco
        {
            Id = e.Id,
            EditThis = e.EditThis
        };

No other columns will be returned.

Similarly for save:

var e = new MyEntity { Id = 123 };
Context.AttachTo("Entities", e);
// anything from here on gets saved
e.EditThis = "Edited";
Context.SaveChanges();
Craig Stuntz
Aha, Craig, we were slowly converging to something similar to what you propose (main difference is that we are using self-tracking entities), I was wondering if this was a good road to follow, so many thanks for confirming so. :-)
Edgar Sánchez

related questions