C# EF Core 3:配置导航属性的备份字段

C# EF Core 3:配置导航属性的备份字段,c#,entity-framework-core,domain-driven-design,ef-core-3.1,C#,Entity Framework Core,Domain Driven Design,Ef Core 3.1,考虑下面的类。它试图保护对_分配的光线的访问 实际上,它工作得很好,因为EF会根据约定自动将支持字段\u assignedTrays链接到属性assignedTrays() 但这给了我以下例外: System.InvalidOperationException: The property 'Rack.AssignedTrays' is of type 'IReadOnlyList<Tray>' which is not supported by current database p

考虑下面的类。它试图保护对_分配的光线的访问

实际上,它工作得很好,因为EF会根据约定自动将支持字段
\u assignedTrays
链接到属性
assignedTrays
()

但这给了我以下例外:

System.InvalidOperationException: The property 'Rack.AssignedTrays' is of type 'IReadOnlyList<Tray>' which 
is not supported by current database provider. Either change the property CLR type or ignore the property
using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
System.InvalidOperationException:属性“Rack.AssignedTrays”的类型为“IReadOnlyList”,该属性
当前数据库提供程序不支持。更改属性CLR类型或忽略该属性
使用“[NotMapped]”属性或在“OnModelCreating”中使用“EntityTypeBuilder.Ignore”。

我错过了什么?它不应该工作吗?

文档没有反映实际的规则,因为
(“标准”C#支持字段命名约定)得到了明确的支持,甚至可能具有最高的优先级

但假设您的命名约定不受支持。您仍然可以映射支持字段,但不能使用
Property
fluent API,因为根据EF核心术语,导航属性不是“属性”,而是“导航”。这适用于所有fluent、更改跟踪等API

为了配置导航,您需要访问关系生成器。然后,您可以使用关联元数据的
PrincipalToDependent
DependentToPrrncipal
属性来访问/配置关系的两端

或者直接使用元数据API(目前没有专门的fluent API)

例如:

modelBuilder.Entity<Rack>()
    .FindNavigation(nameof(Rack.AssignedTrays))
    .SetField("assignedTrays");
modelBuilder.Entity()
.FindNavigation(名称(机架分配射线))
.SetField(“指定光线”);

我认为你真的无能为力。解决方法是重命名backing字段,例如
internalAssignedTrays
,并添加一条注释,说明为什么不能将其称为其他名称,这样它将通过代码审阅。我可以进行不同的映射(
Property
方法不适用于导航属性),但无需,由于EF核心约定。@IvanStoev但是该约定不允许没有下划线的约定。@DavidG Oops,文档似乎不完整,
(默认的C#backing field命名约定)也受支持-可能具有最高优先级。@IvanStoev:你说得对。我想知道为什么集成测试在不使用
HasField
配置时变为绿色,但我将其归咎于“不完整的测试”。。。
System.InvalidOperationException: The property 'Rack.AssignedTrays' is of type 'IReadOnlyList<Tray>' which 
is not supported by current database provider. Either change the property CLR type or ignore the property
using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
modelBuilder.Entity<Rack>()
    .FindNavigation(nameof(Rack.AssignedTrays))
    .SetField("assignedTrays");