If I have something like:
var query = from children in _data.Children where children.ChildId == childId select new CustomModel.MyChild { ChildId = children.ChildId, Name = children.ChildName }; return query.FirstOrDefault();
Where I want the resultant object to be my custom model.
Can I handle the custom model instantiation in a different method, which could be reused if I had multiple linq queries that all generated a custom child model?
For example,
var query = from children in _data.Children where children.ChildId == childId select CreateMyCustomChild([param ??]); return query.FirstOrDefault();
This may well be impossible, I don’t know, but what would the method signature be like if it is possible?
I’m only thinking reuse for when multiple linq queries contain duplicate object initialisation code.
Thanks
It really depends on what version of LINQ you’re using. If you’re using LINQ to SQL, I don’t believe you can call arbitrary methods in the query. The query translator wouldn’t know what to do with the method call
If you’re using LINQ to Objects, you’re absolutely fine to do it, like this:
(Side note: I’d call the range variable in the query ‘child’ rather than ‘children’ as at any one time it only represents a single child.)