gpt4 book ai didi

c# - 另一个虚拟属性的 CodeFirst 访问属性

转载 作者:太空宇宙 更新时间:2023-11-03 15:38:29 25 4
gpt4 key购买 nike

我在 CodeFirst 脚手架 ASP.NET MVC 站点中使用了以下模型(简化):

Public Tax
{
public int ID {get; set; }
public string Name {get; set; }
public decimal Rate {get; set; }
}

Public OrderLine
{
public int ID {get; set; }

public int TaxID {get; set; }
public virtual Tax Tax {get; set; }

public decimal Quantity {get; set; }
public decimal Price {get; set; }

[ScaffoldColumn(false)]
public decimal Amount
{
get { return Quantity * Price; }
set { }
}

[ScaffoldColumn(false)]
public decimal AmountWithTax
{
get { return Amount + (Amount * Tax.Rate / 100); }
set { }
}
}

AmountAmountWithTax 是计算属性,我不需要在 UI 中使用它们,但我需要将它们保存在数据库中。问题是,当我创建一个新的 OrderLine 时,属性 Tax 为空(TaxID 已填充并包含 int 值)所以 AmountWithTax 抛出异常。

如何访问 Rate 属性?

重现步骤:

将这两个模型添加到标准的 ASP.NET MVC EF 项目中,使用右键单击创建脚手架项 -> 添加 > 新建脚手架项... -> MVC5 ... 使用 EntityFramework -> 并在模型中选择模型类。

Visual Studio 将生成 Controller 和 View ,如果 OrderLine 由 Create View 创建,则会在属性 Tax.Rate 上抛出 NullReferenceException,因为 Tax 为 null

最佳答案

您应该使用 ViewModel,而不是实体模型。使用将您想要的属性映射到实体模型的 View 模型应该会为您修复它。

如果您不想这样,您可以按照 How do you exclude properties from binding when calling UpdateModel()? 中的说明排除属性的绑定(bind)。 :

[Bind(Exclude="Amount,AmountWithTax")]

这将使模型绑定(bind)器忽略这些属性,导致它们的 set 不被调用。

顺便说一句,AmountAmountWithTax 的 setter 将导致 StackOverflowException,因为它们正在为自己赋值。您也可以通过简单地删除 set 将它们设置为只读。

关于c# - 另一个虚拟属性的 CodeFirst 访问属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31023054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com