代码之家  ›  专栏  ›  技术社区  ›  Chris Sainty

在Entry Framework Core 2.1中处理IReadonlyCollection属性

  •  5
  • Chris Sainty  · 技术社区  · 8 年前

    我有以下域实体:

    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应该只使用backing字段?

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

    我真的错了吗?任何建议都会受到赞赏。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Ivan Stoev    8 年前

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