Get field from dynamically/programatically named column name and Sum with EF

自古美人都是妖i 提交于 2019-12-11 19:55:02

问题


Today I done it here: Get field from dynamically/programatically named column name with Entity Framework

I referrenced it because this question is very similiar to it.

I would like to get all int values from specific column and sum them and return the value... I how can I do it?

For Example:

string column_name = "Col1";
int meterID = 6;

As old method: "SELECT SUM(column_name) FROM table_name Where MeterID = meterID;"


回答1:


If you have a class

public class TableName
{
    public int MeterId { get; set; }

    public int ColumnName { get; set; }
}

and a DbContext

public class MyDbContext : DbContext
{
    public IDbSet<TableName> TableName { get; set; }
}

you can produce the given query by doing

public int GetSum(int meterId)
{
    return context.TableName.Where(x => x.MeterId == meterId).Sum(x => x.ColumnName);
}


来源:https://stackoverflow.com/questions/22383198/get-field-from-dynamically-programatically-named-column-name-and-sum-with-ef

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!