开发者

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 rul开发者_如何学Ce 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!


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.


I think your column value is based on two mapped properties. Use NotMappedAttribute to Exclude a Property from the Database Schema and Load values in runtime.

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

     [NotMapped]
     public int Value 
     {   
       get return Comments.Count * 2 + Readers.Count;
     }
 }


You may use the DatabaseGenerated attribute and then create triggers in the db for calculating the Value. You can create the triggers in the migrations, or db seed method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜