Get field from dynamically/programatically named c

2019-09-01 10:22发布

问题:

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);
}