So I've started to add Entity Framework 4 into a legacy web application (ASP.NET WebForms).
As a start I have auto-generated some entities from the database. Also I want to apply Repository Pattern.
There is an entity called Visitor
and its repository VisitorRepository
In VisitorRepository I have the following method:
public IEnumerable<Visitor> GetActiveVisitors()
{
var visitors =
from v in _context.Visitors
where v.IsActive
select new Visitor
{
VisitorID = v.VisitorID,
EmailAddress = v.EmailAddress开发者_如何学Go,
RegisterDate = v.RegisterDate,
Company = v.Company,
Position = v.Position,
FirstName = v.FirstName,
LastName = v.LastName
};
return visitors.ToList();
}
Please note that Visitor has more properties than those, I just don't want to get everything because there are some heavy TEXT fields.
That List is then bound to a repeater and when trying to do <%# Eval('EmailAddress') #%>
it throws the following exception.
The entity or complex type 'Model.Visitor' cannot be constructed in a LINQ to Entities query.
A) Why is this happening? How I can workaround this? Do I need to select an anonymous type and then use that to partially initialize my entities??? I don't want to make a SELECT * because there are some heavy TEXT columns I don't need here
B) Why every example I've seen makes use of 'select new' (anonymous object) instead of initializing a known type? Anonymous types are useless unless you are retrieving the data and showing it in the same layer. As far as I know anonymous types cannot be returned from methods? So what's the real point of them???
Thank you all
a) It's happening because Visitor is an entity. You could say the following with the understanding that you won't be able to update the database via the resulting objects outside the data context in the repository:
var visitors =
from v in _context.Visitors
where v.IsActive
select v;
b) I don't know what example you are looking at but you are right to say that passing a collection of anonymous types from a repository in the data layer to the GUI isn't what you want. You can either use self-tracking entities or data transfer objects (DTOs). This MSDN article explains your options in detail.
精彩评论