将导航属性映射到主表

编程入门 行业动态 更新时间:2024-10-27 17:13:08
本文介绍了将导航属性映射到主表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个 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); } });

更多推荐

将导航属性映射到主表

本文发布于:2023-11-17 05:39:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1609019.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   到主表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!