首页 > 解决方案 > ASP.NET Core adding calculations in my properties model and having it as a column in database

问题描述

In ASP.NET Core, I have properties that are calculated based on other properties, for example, I have

public class Worker
{
  public int Id {get;set;}
  public double Rev {get;set;}
  public double Cost {get;set;}
  public double Profit {get;set;}
}

and Profit is meant to be Rev - Cost and for awhile I've been working on a problem where basically either calculations were not performed or the column would not exist. I would have in my Create action something like this

public async Task<IActionResult> Create([Bind("Id,Rev,Cost,Profit")] Worker worker)
{
    if (ModelState.IsValid)
    {
       Worker employee = new Worker
       {
          Rev = worker.Rev,
          Cost = worker.Cost,
          Profit = worker.Rev - worker.Cost
       };
       _context.Add(employee);
       await _context.SaveChangesAsync();
       return RedirectToAction(nameof(Index));
}

By doing this, everything would show up in my database and look fine, however Profit would not be calculated and would be 0. If I change my controller and do not calculate Profit in the controller and instead calculate it in the model it all works like so

public class Worker{
    public int Id {get;set;}
    public double Rev {get;set;}
    public double Cost {get;set;}

    public double Profit{
       get
          {
             return Rev - Cost;
          }
    }
}

It all works and the calculations are performed but Profit is not column in my Worker table. My Question is, how do I perform the calculations in the model but still save Profit as a column in the database, I need both a get; set; but I am not sure how to implement the set while performing and saving the calculations?

标签: c#asp.net-coreproperties

解决方案


您需要引入一个支持字段。在您上面的示例中,您的模型最终将看起来像这样:

public class Worker
{
    public int Id { get; set; }
    public double Rev { get; set; }
    public double Cost { get; set; }

    private double _profit;
    public double Profit
    {
        get
        {
            return Rev - Cost;
        }
        set
        {
            _profit = value;
        }
    }
}

如果您使用的是 EF Core 3.0+ 版本,则需要告诉 EF 使用计算属性而不是支持字段:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder
        .Entity<Worker>()
        .Property(e => e.Profit)
        .UsePropertyAccessMode(PropertyAccessMode.Property);
}

来源:https ://github.com/dotnet/efcore/issues/18998


推荐阅读