Say I have a list of an object with 30 properties (eg: Items
)
If I am using LINQ Query-Syntax to Join
another object (eg: Store
), it seems inevitable that i have to re-assign every property from the Item
, right?
For example:
var temp = from a in items
join b in stores on a.storeKey = b.storeKey into b2
from c in b2.DefaultIfEmpty()
select new ItemViewModel()
{
p1 = a.p1,
p2 = a.p2,
....
p30 = a.p2, //re-assign 30 times (T.T)
storeInfo1 = c.storeInfo1 //all i want is 1 or 2 additional info from store
}
You could use a library such as AutoMapper. For property names that are the same between a
and ItemViewModel
it can do the mapping for you using reflection, for properties with different names you can define a manual mapping, and for properties coming from the other objects (b and c) you can use a helper.
Something like this:
var temp = from a in items
join b in stores on a.storeKey = b.storeKey into b2
from c in b2.DefaultIfEmpty()
select CreateModelFrom(a, b, c);
public ItemViewModel CreateModelFrom(ObjA a, ObjB b, ObjC c)
{
var model = Mapper.Map<ObjA, ItemViewModel>();
model.xxx = b.xxx;
model.storeInfo1 = c.storeInfo1;
return model;
}