ios85
ios85

Reputation: 2134

Mapping Entity Types to a projection

I was reading through a tutorial and they said that you shouldn't ever use an entity type to map to a projection. So something like this isnt allowed (where product is an entity created class):

from p in db.Products
               where p.ProductID== ProductID
               select new Product { Name = p.Name};

So I would create a new class that had something like this:

public string Name { get; set; }

Then use a query like this:

from p in db.Products
            where p.ProductID == ProductID
            select new SomeNewClassName { Name = p.Name });

Is this really necessary, or is this just extra work? If I were to create this class it would hold the exact same properties as my Entity Object, so what is the point then? If it is required what is the naming convention that I use with this new class since it is almost identical to my Entity class. Also should I not use the Entity Object to create a strongly type view in a ASP.net MVC Project?

Upvotes: 0

Views: 1078

Answers (1)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93424

What they mean is that you don't want to use an actual entity type as a projection. You should not, for example, project to an Address entity from a Person entity.

Projection means you are "shaping" the results to be different from their original. If you are simply returning the original entity, then that's not projection. You simply do this:

from p in db.Products
        where p.ProductID == ProductID
        select p;

As for the view, no. In general, you should not pass entities directly to your views. There are a number of philosophical and security reasons why you shouldn't, but in most cases just don't. If you're creating a proof of concept, or it's a trivial internal app, you might be able to get away with it, but any internet facing app should not.

You should create a separate view model, even if it's exactly the same as the entity. I know it's extra work, but in the long run it pays off, because at some point you will probably want a view model that is different from your entity, then you have to rework things even more.

Upvotes: 5

Related Questions