C# ASP.NET Core在我的属性模型中添加计算并将其作为数据库中的列
在ASP.NET Core中,我有基于其他属性计算的属性,例如C# ASP.NET Core在我的属性模型中添加计算并将其作为数据库中的列,c#,asp.net-core,properties,C#,Asp.net Core,Properties,在ASP.NET Core中,我有基于其他属性计算的属性,例如 public class Worker { public int Id {get;set;} public double Rev {get;set;} public double Cost {get;set;} public double Profit {get;set;} } 而利润意味着Rev-成本,有一段时间我一直在研究一个问题,基本上要么没有进行计算,要么列不存在。我会在我的操作中创建类似的内容 publi
public class Worker
{
public int Id {get;set;}
public double Rev {get;set;}
public double Cost {get;set;}
public double Profit {get;set;}
}
而利润
意味着Rev-成本
,有一段时间我一直在研究一个问题,基本上要么没有进行计算,要么列不存在。我会在我的操作中创建类似的内容
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));
}
这一切都起作用,并执行了计算,但我的Worker
表中没有列利润
。我的问题是,如何在模型中执行计算,但仍将利润
保存为数据库中的一列,我需要一个get;设置
但我不确定在执行和保存计算时如何实现设置
?我可以建议您在数据库表中创建,因此每当您为Rev
和成本
列插入新值时,利润
列将自动计算,如下所示:
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;
}
}
}
ALTER表dbo.Worker
增加利润作为成本;
这样,您就可以在表中插入Rev
和Cost
值,而不用担心计算。
稍后,您只需将利润
值读取到模型->利润属性中,方法与从SQL
表读取其他属性相同。您需要引入一个支持字段。在上面的示例中,您的模型最终将显示如下所示:
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使用computed属性,而不是backing字段:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<Worker>()
.Property(e => e.Profit)
.UsePropertyAccessMode(PropertyAccessMode.Property);
}
模型创建时受保护的覆盖无效(ModelBuilder ModelBuilder)
{
建模者
.实体()
.不动产(e=>e.利润)
.UsePropertyAccessMode(PropertyAccessMode.Property);
}
来源:我以前尝试过这个,但我不知道怎么做,谢谢你给我看!谢谢你的建议,我想我会尝试另一种方式。不过,我会把它记在笔记里,以备将来参考。