sau*_*rox 4 c# entity-framework-core
我有一个名为 ItemEntity 的实体类,其中有 2 列:价格和数量。我想以这样的方式添加名为 amuount 的第三列amount = rate*quantity。我是这样做的:
这是完整的实体类:
namespace Services.Common.Billing.Entities;
public class ItemEntity : BaseEntity
{
public int FeeType { get; set; }
public int FeeSchedule { get; set; }
public int FeeUnit { get; set; }
public String Description { get; set; }
public Decimal Quantity { get; set; }
[Display(Name = "Rate(US$)")]
public Decimal Rate { get; set; }
public Decimal Amount { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这是 dbContext 类:
public class BillingDbContext : DbContext
{
public BillingDbContext(DbContextOptions<BillingDbContext> options) : base(options)
{
}
public DbSet<ItemEntity>? Items { get; set; }
//Any seed data goes here
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ItemEntity>().Property(e => e.Amount).HasComputedColumnSql("Items.Rate * Items.Quantity", stored: true);
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在API中使用实体类时自动将金额保存到数据库中?金额的值应该是quantity*rate。
任何帮助都会非常明显。
如果数据库支持,您可以使用计算列,例如使用影子属性:
modelBuilder.Entity<MyEntity>()
.Property<decimal>("AmountCol")
.HasComputedColumnSql("Rate * Quantity", stored: true);
Run Code Online (Sandbox Code Playgroud)
请注意,stored: true结果会在每次更新行时计算,并与常规列一起存储在磁盘上,因为false(默认)会创建一个虚拟计算列,每次从数据库获取时都会计算其值。
| 归档时间: |
|
| 查看次数: |
187 次 |
| 最近记录: |