处理 EfCore 2.1 中的 IReadOnlyCollection 属性 [英] Dealing with IReadOnlyCollection property in EfCore 2.1

查看:10
本文介绍了处理 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();

我对订单项进行了以下配置:

I have the following configuration for the line items:

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

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

However, when I run my app I'm getting the following error:

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 应该只根据我的配置使用支持字段?

My understanding is that EF should only be using the backing field per my configuration?

我尝试添加 [NotMapped] 属性只是为了看看发生了什么,但没有奏效.

I have tried adding the [NotMapped] attribute just to see what happened, but that didn't work.

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

Am I really wrong with this? Any pointers would be appreciated.

推荐答案

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

It's possible to configure a backing field usage for a navigation property, but not via Property method which is for primitive property, and not via fluent API (doesn't exist at this time), but directly through mutable model metadata associated with the relationship:

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

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

You can also set the mode for all entity navigation properties (you can still override it for individual properties) by using:

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

这篇关于处理 EfCore 2.1 中的 IReadOnlyCollection 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆