计算列在EF代码第一 [英] Calculated column in EF Code First
问题描述
我需要在数据库中将一列数据库计算为(行总和) - (行数之和)。我正在使用代码优先模型来创建我的数据库。
I need to have one column in my database calculated by database as (sum of rows) - (sum of rowsb). I'm using code-first model to create my database.
这是我的意思:
public class Income {
[Key]
public int UserID { get; set; }
public double inSum { get; set; }
}
public class Outcome {
[Key]
public int UserID { get; set; }
public double outSum { get; set; }
}
public class FirstTable {
[Key]
public int UserID { get; set; }
public double Sum { get; set; }
// This needs to be calculated by DB as
// ( Select sum(inSum) FROM Income WHERE UserID = this.UserID)
// - (Select sum(outSum) FROM Outcome WHERE UserID = this.UserID)
}
如何在EF CodeFirst ?
How can I achieve this in EF CodeFirst?
推荐答案
您可以创建计算列在您的数据库表中。在EF模型中,您只需使用 DatabaseGenerated
属性注释相应的属性:
You can create computed columns in your database tables. In the EF model you just annotate the corresponding properties with the DatabaseGenerated
attribute:
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public double Summ { get; private set; }
或使用流畅的映射:
modelBuilder.Entity<Income>().Property(t => t.Summ)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed)
根据 Matija Grcic 的建议,评论,这是一个好主意,使财产私人集
,因为你可能永远不想在应用程序代码中设置它。实体框架与私有设置者无关。
As suggested by Matija Grcic and in a comment, it's a good idea to make the property private set
, because you'd probably never want to set it in application code. Entity Framework has no problems with private setters.
这篇关于计算列在EF代码第一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!