在Entiry Framework Core 2.1中处理IReadOnlyCollection属性 [英] Dealing with IReadOnlyCollection property in Entiry Framework Core 2.1

查看:125
本文介绍了在Entiry Framework Core 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.

我真的这是错的吗?

推荐答案

可以为导航属性配置后备字段用法,但不能通过 Property 方法用于原始属性,而不是通过流畅的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);

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

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