views:

111

answers:

1

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();
}

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

+1  A: 

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.

Tom Cabanski
I guess my question was not clear enough. I know I can select the whole entity like that, but I just want to get some fields (not SELECT *) because there are some heavy TEXT fields I don't need. I've updated my question.
emzero
@Tom is still correct, to select only a few fields you must [project onto](http://blogs.teamb.com/craigstuntz/2009/12/31/38500/) a *non-entity* type.
Craig Stuntz
Yes, I didn't know I couldn't project onto an entity type. So I guess I would create POCO classes to project to.
emzero
POCOs or anonymous types; either one.
Craig Stuntz