How to create a repeating Entity Framework projection expression?

My database has tables with dozens of columns:

Table MyEntity: int Id string Name string Email ...dozens of other columns I never use in this project

The class generated by EF has properties for additional columns, and a simple query gets all the extra columns, wastefully.

Instead, I want to have a thin class, for example:

class MyEntity { public int Id; public string Name; public string Email; }

When I request, I want to instantiate my thin object, and obviously I can do this:

from x in MyEntity
select new MyEntity {Id = x.Id, Name = x.Name, Email = x.Email };

But I do it a lot, and when I enter properties every time it becomes very tedious (and prone to errors, because I can forget it).

So I'm trying to do something like this:

from x in MyEntity
select x.ToLiteEntity();

But I'm not sure how to write ToLiteEntityit so that it creates an expression that is added to the query, so that it knows that only the columns you need are needed to select it. How can i do this?

+4
2

. "lite", :

public IQueryable<MyEntity> GetLiteMyEntities(DbContext c, string Name) // your implementation of DbContext, not actually DbContext
{
    return from me in c.MyEntity 
        select new MyEntity {Id = x.Id, Name = x.Name, Email = x.Email };
}

EDIT: , , , , IQueryable:

public IQueryable<MyEntity> GetLiteMyEntities(IQueryable<MyEntity> query)
{
    return from me in query 
        select new MyEntity {Id = x.Id, Name = x.Name, Email = x.Email };
}

// build your filter first
from x in MyEntity 
where x.someSpecialID == 42
select x;

// then pass it to get your lite object
var lite = GetLiteMyEntities(x);

, :

public IQueryable<MyEntity> GetLiteMyEntities(this IQueryable<MyEntity> query)
{
    return from me in query 
        select new MyEntity {Id = x.Id, Name = x.Name, Email = x.Email };
}

var lite = (from x in MyEntity 
where x.someSpecialID == 42
select x).GetLiteMyEntities();
+2

Queryable Extensions AutoMapper

.ProjectTo() AutoMapper select IQueryable, Name , , IQueryable OrderLineDTO Select.

+1

Source: https://habr.com/ru/post/1624155/


All Articles