Get field from dynamically/programatically named c

2019-09-01 10:55发布

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条回答
我只想做你的唯一
2楼-- · 2019-09-01 11:04

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);
}
查看更多
登录 后发表回答