c# - 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?
解决方案
您需要引入一个支持字段。在您上面的示例中,您的模型最终将看起来像这样:
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);
}
推荐阅读
- javascript - 将从相机拍摄的图像转换为画布的侧面有灰色
- hadoop - 将文件从 Google Cloud Storage 加载到本地 Hadoop 集群
- azure - Web 服务器和电子邮件托管在不同的服务器中
- c - gcc:链接时替换
- c++ - VS 2017 错误 C2664 地图插入尝试
- ffmpeg - 第一个输入流中具有高延迟的ffmpeg
- c++ - 我的 c-string 复制函数正在破坏其他变量的堆栈
- cassandra - 如何仅在 Cassandra 中存储最近的条目?
- python - Python Pandas - 将大型数据框导出到 Excel 工作表
- java - 是否可以访问具有私有构造函数的类中的私有变量并从另一个类更改最终变量值