Calculated column in EF Code First

后端 未结 7 1418
半阙折子戏
半阙折子戏 2020-11-28 05:16

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.

Here is what I

7条回答
  •  盖世英雄少女心
    2020-11-28 06:10

    As of 2019, EF core allows you to have computed columns in a clean way with the fluent API:

    Suppose that DisplayName is the computed column you want to define, you have to define the property as usual, possibly with a private property accessor to prevent assigning it

    public class Person
    {
        public int PersonId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        // this will be computed
        public string DisplayName { get; private set; }
    }
    

    Then, in the model builder, address it with the column definition:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity()
            .Property(p => p.DisplayName)
            // here is the computed query definition
            .HasComputedColumnSql("[LastName] + ', ' + [FirstName]");
    }
    

    For further information, have a look at MSDN.

提交回复
热议问题