在Entiry Framework Core 2.1中处理IReadOnlyCollection属性

Chr*_*nty 6 entity-framework entity-framework-core

我有以下域实体:

public string Reference { get; private set; }
public int SupplierId { get; private set; }
public int BranchId { get; private set; }
public Guid CreatedBy { get; private set; }
public DateTime CreatedDate { get; private set; }
public Source Source { get; private set; }
public OrderStatus OrderStatus { get; private set; }
public decimal NetTotal { get; private set; }
public decimal GrossTotal { get; private set; }

private List<PurchaseOrderLineItem> _lineItems = new List<PurchaseOrderLineItem>();
public IReadOnlyCollection<PurchaseOrderLineItem> LineItems => _lineItems.AsReadOnly();
Run Code Online (Sandbox Code Playgroud)

订单项的配置如下:

builder.Property(x => x.LineItems)
       .HasField("_lineItems")
       .UsePropertyAccessMode(PropertyAccessMode.Field);
Run Code Online (Sandbox Code Playgroud)

但是,当我运行我的应用程序时,出现以下错误:

The property 'PurchaseOrder.LineItems' is of type 'IReadOnlyCollection<PurchaseOrderLineItem>' 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'.
Run Code Online (Sandbox Code Playgroud)

我的理解是,EF应该仅根据我的配置使用备份字段吗?

我尝试添加[NotMapped]属性只是为了查看发生了什么,但这没有用。

我真的错了吗?任何指针将不胜感激。

Iva*_*oev 4

可以为导航属性配置支持字段用法,但不能通过Property原始属性的方法,也不能通过 Fluent API(目前不存在),而是直接通过与关系关联的可变模型元数据:

modelBuilder.Entity<PurchaseOrder>()
    .HasMany(e => e.LineItems)
    .WithOne(e => e.PurchaseOrder) // or `WithOne() in case there is no inverse navigation property
    .Metadata.PrincipalToDependent.SetPropertyAccessMode(PropertyAccessMode.Field); // <--
Run Code Online (Sandbox Code Playgroud)

您还可以使用以下方法设置所有实体导航属性的模式(您仍然可以覆盖单个属性):

modelBuilder.Entity<PurchaseOrder>()
    .Metadata.SetNavigationAccessMode(PropertyAccessMode.Field);
Run Code Online (Sandbox Code Playgroud)