Why LINQ to Entities won't let me initialize just some properties of an Entity?
Posted
by emzero
on Stack Overflow
See other posts from Stack Overflow
or by emzero
Published on 2010-04-29T01:25:01Z
Indexed on
2010/04/29
1:37 UTC
Read the original article
Hit count: 1437
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,
RegisterDate = v.RegisterDate,
Company = v.Company,
Position = v.Position,
FirstName = v.FirstName,
LastName = v.LastName
};
return visitors.ToList();
}
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 initialize my entities???
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
© Stack Overflow or respective owner