如何访问 EF Core 2.2 中的链式/嵌套属性 [英] How to access chained/nested property in EF Core 2.2

查看:35
本文介绍了如何访问 EF Core 2.2 中的链式/嵌套属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

public class Vehicle{
    public Engine TurboV6 { get; set; }

public class Engine{
    public Cylinder Core { get; set; }

public class Cylinder{
    public double? Capacity { get; set; }

并且我在 OnModelCreating 方法中如下配置了拥有的实体:

And I have configured the owned entities as below in OnModelCreating method:

    modelBuilder.Entity<Vehicle>()
                .OwnsOne(
                    v => v.TurboV6, e=> {
                        e.OwnsOne(e => e.Core);
                    });

问题

当我尝试在拥有的实体中保存空值时,例如 v.TurboV6.Core = null; EF Core 不会在 Vehicle.TurboV6.Core.Capacity 中保存空值 为空,而不是以前的值保留在数据库中.我认为这是由 EF Core 的更改跟踪问题引起的.

When I tried to save a null value in the owned entity like v.TurboV6.Core = null; EF Core does not save null value in the Vehicle.TurboV6.Core.Capacity as null, instead the previous value persists in the database. I assume this is caused by a problem in EF Core's change tracking.

我试图用以下方法克服这个问题:

I tried to overcome this with :

vContext = DbContext.Vehicles.Add(new Vehicle());
vContext.Property(v => v.TurboV6.Core.Capacity).IsModified = true;

请注意,vContextEntityEntry 类型,而不是 DbContext.

Take note that vContext is EntityEntry<Vehicle> type, not DbContext.

类似于这个问题:嵌套导航使用实体条目引用的属性

当我访问以下代码时:

vContext.Property(v => v.TurboV6.Core.Capacity).IsModified = true;

我收到一条错误消息说

System.ArgumentException : 表达式 'v =>v.TurboV6.Core.Capacity' 不是有效的属性表达式.表达式应该代表一个简单的属性访问:'t =>t.MyProperty'.(参数'propertyAccessExpression')

System.ArgumentException : The expression 'v => v.TurboV6.Core.Capacity' is not a valid property expression. The expression should represent a simple property access: 't => t.MyProperty'. (Parameter 'propertyAccessExpression')

我使用的是 EF Core 2.2.6

I am using EF Core 2.2.6

是否可以像上面那样映射链式属性?我错过了什么吗?如果是,我该怎么做?

Is it possible to map chained property like above? Have I missed anything? If yes, how do I do so?

谢谢

推荐答案

TurboV6Corereference navigation 属性,所以它们必须是通过访问参考方法.嵌套实体条目可通过 TargetEntry 属性.重复此操作,直到到达可以使用 Property 方法的所需级别条目.

TurboV6 and Core are reference navigation properties, so they must be accessed through Reference method. The nested entity entry is accessible through TargetEntry property. Repeat that until you get to the desired level entry on which you can use Property method.

像这样:

vContext
    .Reference(e => e.TurboV6).TargetEntry
    .Reference(e => e.Core).TargetEntry
    .Property(e => e.Capacity).IsModified = true;

这篇关于如何访问 EF Core 2.2 中的链式/嵌套属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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