What's the difference between saving a Func as a variable and then passing it to a entity framework select opposed to typing the conversion inline inside of the select.
Func<Models.Contact,ViewModels.Contact> ToViewModel =
c => new ViewModels.Contact()
{
ID = c.ID,
...
UserName = c.User.UserName
};
...
return dc.Contacts.Select(ToViewModel);
as opposed to
return dc.Contacts.Select(c => new ViewModels.Contact()
{
ID = c.ID,
...
UserName = c.User.UserName
});
I ask this because although both methods work, they have subtly different reaction to nulls and a few other things and I can't understand why.
For example in this case, a Contact may or may not have a User, so User may or may not be null. When typing the initialiser inline it will fail the property gracefully to null. However when passing the same initializer via the variable it will throw a NullReferenceException.
Why is this?
Note that the reason I want to save the initialiser is so that it can be reused in each of the CRUD operations for returning an object from a WebApi. It would be annoying to have to copy and paste the select around the class, especially if over time properties need to be added or removed from the response.