0

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;"

4
  • What is the "example" supposed to mean? What have you tried? Commented Mar 13, 2014 at 15:24
  • I would like to SUM a column's datas with EF. I want to specify column name with variable. That's what ı want to do. tSQL is an old example to understand. I would like to do it with EF. Thanks Commented Mar 13, 2014 at 15:26
  • Why would you want to specify column with a variable when you can use a lambda? Commented Mar 13, 2014 at 15:28
  • what's lambda? i dont have info Commented Mar 13, 2014 at 15:29

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for respond, but this method coming easist to me: stackoverflow.com/questions/22377804/… Could you give an example with this method too please?
That's not possible with Entity Framework, you cannot use reflection to create queries like that. What EF sees is the .Where().Sum() part, then it will translate that into SQL to query the database. An alternative would be to fall down to regular SQL queries, but then the whole purpose of EF is gone IMO.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.