views:

187

answers:

1

Hi guys

Short Question:

Basically I am trying to add a scalar property to my entity which holds the ID of a FK entity.

What I have tried to do thus far:

What I have tried so far is adding the scalar property (called ChildId) and mapped it to the matching column in the database. Now as you can imagine I get some exceptions when I try and do this because entity framework complains that the FK id is being managed in two places, once through x.ChildId and the other through x.Child.ChildId.

Now I get why it is doing this but I need some why to be able to have a scalar property which is automatically populated with the ChildId.

What I know I could do but really don't want to:

I realize that I could write a linq query that does something like the following (where I have implemented the other half of the partial class and added a property there called ChildId):

from x in db.Parent
select new Parent { ParentName = x.ParentName, ..., ChildId = x.Child.ChildId }

But this is extremely messy, particular when I have 30 odd queries that return a parent object, this mapping would need to be repeated for each query...

Also I realize that after I have executed the query I could go something like:

var childId = parent.Child.Id;

But this would cause either an extra query to be triggered, or if I was proactively loading child, and in either case I would be pulling out a lot more data than I need when I only want the ID...

The required end result:

So how do I get around some of these limitations so that I can write my queries like so (or something very similar):

from x in db.Parent
select x

And have it so that I can either go:

var childId = parent.Child.Id;   //Where in this case the only property retrieved would be the Id 
//Or
var childId = parent.ChildId;

Cheers Anthony

EDIT:

Hey thanks for the reply...

I just figured this out for myself as well. Basically I was thinking that if EF supports lazy loading it must be storing the ID somewhere. Then it clicked that it must be in the reference... Hence for me it worked out being something like:

destination.PlanTypeId = (int)source.PlanTypeReference.EntityKey.EntityKeyValues[0].Value;

Also thanks for the idea of creating the extension property... will be very useful.

+1  A: 

Did you try using parent.ChildReference.EntityKey? It doesn't need to be additionaly loaded and is holding FK. You can write extension method to get key easier.

LukLed