2

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.

4

1 回答 1

4

您的第二个示例编译为Expression<Func<Contact, Contact>>EF 在服务器上运行的 . (使用IQueryable接口)
变成使用OUTER JOIN的SQL查询,不会产生空引用异常。

您的第一个示例不是表达式树,因此它通过IEnumerable<T>接口并在客户端上执行。
您可以通过将其更改ToViewModelExpression<Func<...>>.

于 2012-10-22T15:41:39.290 回答