One thing that frustrated the crap out of us here last week was not being able to go from a child entity to a parent entity easily. That is, until I learned the trick. And there's always a trick, isn't there.
Say you have a collection of warehouses, and each warehouse has a collection of doors. Given a door id (GUID), get the warehouse it is at. The WarehouseID is foreign keyed to the Door table.
You would think (based on LINQ to SQL), that you could go Door.WarehouseID or at the very least Door.Warehouse.WarehouseID... but alas, no can do. EF hides the relationship through an object called an Entity Key. In my brain, this was a little ridiculous, since I knew what my key was, just give it to me.
But I guess this is why I don't design frameworks for a living. The Entity Key is a dictionary collection, of all the keys that make up the relationship. Thus, if you have more than one column in the key, the EntityKEy collection contains both keys, but you can access it to use those values with a little care.
By adding a property to the Door object in a partial class, you can access the dictionary to extract the value. If you have multiple values in your key, be careful to index the Key properly.
public Guid WarehouseID
{
get
{
return new Guid(WarehouseReference.EntityKey.EntityKeyValues[0].Value.ToString());
}
set
{
WarehouseReference.EntityKey = new EntityKey("ContextName.Warehouse", "WarehouseID", value);
}
}
No comments:
Post a Comment