You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 2.0 MVC中如何用属性优化EF货币字段设计?

Optimizing Currency Property Design in EF Core 2.0 MVC

Absolutely! You can clean up this redundant three-property pattern using EF Core's owned types (to map a combined currency-amount type directly to your existing table columns) and simple encapsulation for display logic. Here's how to do it step by step:

1. Create a Reusable CurrencyAmount Class

First, wrap the decimal amount and currency code into a single, cohesive type. This eliminates the need for separate properties on your entity:

public class CurrencyAmount
{
    // Required for EF Core owned types (parameterless constructor)
    public CurrencyAmount() { }

    // Convenience constructor for easy initialization
    public CurrencyAmount(decimal amount, CurrencyCode currency)
    {
        Amount = amount;
        Currency = currency;
    }

    public decimal Amount { get; set; }
    public CurrencyCode Currency { get; set; }

    // Encapsulate your display formatting logic here
    public string DisplayString 
    { 
        get 
        {
            var roundedAmount = Math.Round(Amount, Currency.DecimalDigits);
            return $"{Currency.PreSymbol}{roundedAmount}{Currency.PostSymbol}";
        }
    }
}

2. Configure EF Core to Map CurrencyAmount to Existing Columns

Use EF Core's owned types (supported in 2.0+) to tell EF to map the CurrencyAmount properties directly to columns in your main entity table (no complex relationships or extra tables required). Update your DbContext's OnModelCreating method:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    // Map TotalCost to your existing columns
    modelBuilder.Entity<YourEntity>()
        .OwnsOne(e => e.TotalCost, config =>
        {
            config.Property(ca => ca.Amount)
                .HasColumnName("TotalCost") // Matches your original decimal column name
                .HasColumnType("decimal(18,4)"); // Adjust precision to match your needs

            config.Property(ca => ca.Currency)
                .HasColumnName("CostCurrency"); // Matches your original currency column name
        });

    // Repeat for TotalBill
    modelBuilder.Entity<YourEntity>()
        .OwnsOne(e => e.TotalBill, config =>
        {
            config.Property(ca => ca.Amount)
                .HasColumnName("TotalBill")
                .HasColumnType("decimal(18,4)");

            config.Property(ca => ca.Currency)
                .HasColumnName("BillCurrency");
        });

    // Add other entity configurations as needed
}

3. Simplify Your Entity Class

Now you can replace the six separate properties with two CurrencyAmount properties. Add display attributes as before:

public class YourEntity
{
    // Other entity properties (ID, etc.)...

    [Display(Name = "Total Cost")]
    public CurrencyAmount TotalCost { get; set; }

    [Display(Name = "Total Bill")]
    public CurrencyAmount TotalBill { get; set; }
}

4. Update MVC Views for Display

Since CurrencyAmount has a DisplayString property, you can directly use it in your views:

<p>@Html.DisplayNameFor(m => m.TotalCost): @Model.TotalCost.DisplayString</p>
<p>@Html.DisplayNameFor(m => m.TotalBill): @Model.TotalBill.DisplayString</p>

For even cleaner views, create a display template for CurrencyAmount:

  1. Create Views/Shared/DisplayTemplates/CurrencyAmount.cshtml
  2. Add this content:
@model CurrencyAmount
@Model.DisplayString

Then you can use Html.DisplayFor to automatically render the formatted string:

<p>@Html.DisplayFor(m => m.TotalCost)</p>
<p>@Html.DisplayFor(m => m.TotalBill)</p>

Bonus: Fix Typo in Original Code

Note: In your original code, there are typos (CostCurrencey instead of CostCurrency, BillCurrencey instead of BillCurrency) — the CurrencyAmount class avoids these by encapsulating the logic.

This approach keeps your code DRY, eliminates redundant properties, and maintains the exact same database schema you had before (no extra tables or complex relationships).

内容的提问来源于stack exchange,提问作者Mark Johnson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:42:57