将导航属性映射到主表 [英] Map navigation property to main table

查看:65
本文介绍了将导航属性映射到主表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Contract 类,它具有两个属性 TotalAmount InstallmentAmount

I have class Contract with two properties TotalAmount and InstallmentAmount

public class Contract
{
    public int ContractId { get; set; }
    public Amount TotalAmount { get; set; }
    public Amount InstallmentAmount { get; set; }
    //other Amounts
}

public class Amount
{
    public decimal Value { get; set; }
    public string Currency { get; set; }
} 

是否可以配置Entity Framework,以便它可以创建具有以下结构的表 Contract :

Is it possible to configure Entity Framework so it can create one table Contract with structure like below:

------------------------------------------------------------
| ContractId | TotalAmountValue | TotalAmountCurrency | ... 
|     999    |       1000       |         USD         | ...
------------------------------------------------------------  

推荐答案

回答您的具体问题.通过将 Amount 类映射为

Answering your concrete question. What you are asking is possible by mapping the Amount class as owned entity type.

最简单的方法是使用 [拥有的] 属性:

The simplest way to do that is to use [Owned] attribute:

[Owned] // <--
public class Amount
{
    public decimal Value { get; set; }
    public string Currency { get; set; }
}

或流畅的API:

modelBuilder.Owned<Amount>();

默认情况下,这将创建一个有问题的表,但列名称将为 TotalAmount_Value TotalAmount_Currency 等.如果可以,则您可以完成.

This by default will create a single table in question, but the column names will be TotalAmount_Value, TotalAmount_Currency etc. If that's ok, you are done.

如果要删除列名中的下划线,则需要为每个 Contract.Amount 属性使用 OwnsOne 流利API,然后使用 Property(...).HasColumnName(...)用于每个 Amount 属性.您可以使用EF Core元数据服务循环执行该操作,而不必手动执行该操作.例如:

If you want to remove the underscore in column names, you'd need to use OwnsOne fluent API for each Contract.Amount property and then Property(...).HasColumnName(...) for each Amount property. Instead of doing that manually, you could do that in a loop using the EF Core metadata services. For instance:

modelBuilder.Entity<Contract>(builder =>
{
    var amounts = builder.Metadata.GetNavigations()
        .Where(n => n.ClrType == typeof(Amount));
    foreach (var amount in amounts)
    {
        var amountBuilder = builder.OwnsOne(amount.ClrType, amount.Name);
        var amountProperties = amountBuilder.OwnedEntityType.GetProperties()
            .Where(p => !p.IsKey());
        foreach (var property in amountProperties)
            amountBuilder.Property(property.Name).HasColumnName(amount.Name + property.Name);
    }
});

这篇关于将导航属性映射到主表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆