首页 > 解决方案 > 在 EfCore 2.1 中处理 IReadOnlyCollection 属性

问题描述

我有以下域实体:

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();

我对行项目有以下配置:

builder.Property(x => x.LineItems)
       .HasField("_lineItems")
       .UsePropertyAccessMode(PropertyAccessMode.Field);

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

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'.

我的理解是,EF 应该只根据我的配置使用支持字段?

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

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

标签: entity-frameworkentity-framework-core

解决方案


可以为导航属性配置支持字段使用,但不能通过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); // <--

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

modelBuilder.Entity<PurchaseOrder>()
    .Metadata.SetNavigationAccessMode(PropertyAccessMode.Field);

推荐阅读