1

I would like to store and query a calculated field. For instance, the fallowing table:

public class ModelTest
{
    [Key]
    public int Id { get; set; }

    public int A { get; set; }

    public int B { get { return CSharpFunction(A) ; } } 

}

I want be able to query the values from the table like this.

results = db.ModelTests.Where(m => m.B = 10);

However i got the fallowing error:

The specified type member 'B' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

The only way is to query ALL entries from the db db.ModelTests.ToList() and then selects based on the Where statent later.

Is possible to store the B value into the db and optimize this kind of query ?

(other solutions are welcome too).

thanks

Daniel Santos
  • 14,328
  • 21
  • 91
  • 174
  • Just have a backing property like Get_Prop Value that calculates. I wouldn't map a calculating field to a column like this. I doubt it would even work. You can use [NotMapped] Attribute on it. – Botonomous Apr 17 '17 at 12:57
  • You can create a *computed column* B in the database table if the type of calculation allows it. – Gert Arnold Apr 17 '17 at 20:40

1 Answers1

1

Actually, when you are using linq expressions from your DbContext object you are using linq-to-entities.

Check this other answer. linq to entities vs linq to objects - are they the same?

Community
  • 1
  • 1
joaofs
  • 486
  • 1
  • 7
  • 17
  • As long you are using an IQueryable it's always constructing the result based on an expression tree. – joaofs Apr 17 '17 at 13:21
  • In this case B is not mapped to the entities.. that is why. How can I test what you are saying ? – Daniel Santos Apr 17 '17 at 13:24
  • 1
    if you are able to use `IQueryable results` you can. This article explains it quite well https://blog.falafel.com/understanding-ienumerable-iqueryable-c/ – joaofs Apr 17 '17 at 13:40
  • We understand the difference. However B is not a simple variable. Querying like this, i got the fallowing error. 'The specified type member 'B' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.' That's why I cannot do that. – Daniel Santos Apr 17 '17 at 16:50
  • @DanielSantos You probably better off using a stored procedure then. You can still invoke it using entity framework returning a collection of ModelTest. – joaofs Apr 17 '17 at 20:09