使用 ef core 3.1 添加来自不同表的计算列

Add calculated column from different tables usin ef core 3.1

如果相关 table 中的另一列发生变化,我想计算列值。

Product class:

public class Product
{
    private int totalQuantity;

    private bool quantityAlert;

    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid ProductId { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public int MinimumQuantity { get; set; }
    public string Description { get; set; }
    public string BarCode { get; set; }
    public string ProductCode { get; set; }
    public int CategoryId { get; set; }
    public int UnitId { get; set; }
    public virtual Unit Unit { get; set; }
    public virtual Category Category { get; set; }
    public virtual List<StockProduct> StockProducts { get; set; }

    public int TotalQuantity
    {
        get
        {
            return totalQuantity;
        }
        protected set
        {
            int q = 0;

            foreach (var product in StockProducts)
            {
                q += product.Quantity;
            }
            totalQuantity = q;
        }
    }

    public bool QuantityAlert
    {
        get { return quantityAlert; }
        protected set
        { 
            quantityAlert = TotalQuantity <= MinimumQuantity; 
        }
    }
}

StockProduct class:

public class StockProduct
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid StockProductId { get; set; }
    [Required]
    public int Quantity { get; set; }
    [Required]
    public double BuyingPrice { get; set; }
    public double SellingPrice { get; set; }
    public Guid ProductId { get; set; }
    public virtual Product Product { get; set; }
}

appContext配置:

modelBuilder.Entity<Product>()
    .Property(p => p.TotalQuantity)
    .ValueGeneratedOnAddOrUpdate()
    .UsePropertyAccessMode(PropertyAccessMode.Property);

modelBuilder.Entity<Product>()
    .Property(p => p.QuantityAlert)
    .ValueGeneratedOnAddOrUpdate()
    .UsePropertyAccessMode(PropertyAccessMode.Property);

错误信息是

SQLite Error 19: 'NOT NULL constraint failed: Products.TotalQuantity'.

如果我为总数量和最小数量设置默认值,我会得到同样的错误,但是如果 QuantityAlert 的默认值设置为 false,即使默认总数量 = 0 更少,它仍然是 false比默认最小数量 = 0.

不符合

quantityAlert = TotalQuantity <= MinimumQuantity; 

Entity Framework Core Fluent API ValueGeneratedOnAddOrUpdate 提供了一种方法来指示 selected 属性 的值将在添加新实体时生成数据库或现有数据库被修改。因此,当 EF Core 生成 SQL 时,不应将 属性 包含在 INSERT 或 UPDATE 语句中。这意味着它在您的数据库中有一个默认列值,或者它将由触发器生成。正如我猜你没有任何这些所以你必须从你的数据库上下文中删除 ValueGeneratedOnAddOrUpdate 。并更改您的 TotalQuantity 和 QuantityAlert 属性

 public int TotalQuantity
    {
        get { return  StockProducts==null? 0: StockProducts.Sum(p=>p.Quantity; }
        protected set {}
}
    }
public bool QuantityAlert
    {
        
         get {return   quantityAlert = TotalQuantity <= MinimumQuantity; }
       protected set {}
}
    }

并且不要忘记在任何 select 产品查询中包含 StockProducts。