LINQ for Entities - Best Practices for Passing Models

As we all know, most applications have a level of data access, often using repository classes. Usually we want the repository to work with strongly typed objects, for example.

interface IUserRespository
{
     User GetUserByID(int id);
     void AddUser(User u);
     ... and so on
}

However, sometimes we want to make a more complex query in the database, which includes grouping and aggregation. For example, we want to get the total value of all orders of all users (the result set will contain only two columns: UserName and TotalAmount). Now my question is: what does the repository method look like? There are dozens of LINQ examples on the Internet for entities on how to query a sum and a group, but all of these examples return anonymous types. So how can our repository return the result of such a query? Another common answer: wrap it in a class. Thus, the method might look like this:

interface IUserRepository
{
    UserOrderTotal[] GetOrderTotalsForAllUsers();
}

UserOrderTotal , : UserName TotalAmount. - .cs. ? , "" - (edmx). User , TotalAmount, , :

interface IUserRepository
{
    User[] GetOrderTotalsForAllUsers();
}

, , Name TotalAmount. , , , , . 3004: , 2226: . User.TotalAmount Set User.An Entity with Key (PK) , : Entity is type [FPSoMeterModel.User ]

? , , , ? - (!), , . , LINQ , , ... , , , "" LINQ, - ?

+3
1

UserOrderTotal, . .

(1) UserOrderTotal Data Transfer Object (DTO). , . DTO . . : . MVVM , ViewModel MVVM DTO.

(2) UserOrderTotal . . . , edmx Entity Frameworks (EF). , EF , , , . edmx , edmx.

User: . . , . User, . , . User , : , .

, , EF , . EF ( ), . , , LINQ.

- (!), , .

. - . EF . , EF , . , .

, , , "" LINQ

Ive /-, . / , DTO. " " . " ". . . ( ) . :

void UpdateButton_Click(object sender, EventArgs e)
{
    if (!this.Page.IsValid)
    {
        return;
    }

    var command = new UpdateUserSettingsCommand();

    command.UserName = this.UserName.Text;
    command.MailAddress = this.MailAddress.Text;

    command.Execute();
}

, . , DTO, SO .

, .

+1

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


All Articles