在EF代码首先计算列 [英] Calculated column in EF Code First

查看:379
本文介绍了在EF代码首先计算列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过数据库(行的总和)来计算我的数据库有一列 - (rowsb的总和)。我使用的代码,第一个模型的创建数据库

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葛契奇并在评论,这是一个好主意,使财产私人组,因为你可能永远都不想将其设置为应用程序代码。实体框架与私营制定者没有任何问题。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆