Search code examples
entity-frameworklinq-to-sqllinq-to-entitiesentity-framework-4.1

How to deal with "computed" property in Entity Framework 4.1?


I have a model as below:

public class Post
{
    public int Id {get;set;}
    public virtual ICollection<Comment> Comments {get;set;} 
    public virtual ICollection<Reader> Readers {get;set;}
    public int Value {get;set;}
}

The rule is Value = Comments.Count * 2 + Readers.Count.

What is the right and convenient way to deal with the "computed" property of "Value"?

I think it is the best that the "Value" can be calculated and saved automatically when Comments or Readers add/remove element.

but the "DatabaseGeneratedAttribute" seems no use here.

Thank you!


Solution

  • This is not supported. There is no way to make Value available for linq-to-entities queries if it is not mapped to database column. In case of EF using EDMX for mapping this can be sometimes solved by using custom mapped SQL function or model defined function but code first mapping doesn't support anything of that. Other way is to create database view and map your entity to view but in such case entity will be read only.

    Once you use .NET code for defining value it is always only client side property computed from data loaded from database. If you don't want to recompute property every time you need observable collections with event handler changing precomputed value each time the collection changes.

    DatabaseGenerated attribute just marks your property as generated by database - in such case you cannot change its value and database must ensure that correct value will be stored in your table.