简体   繁体   English

如何访问 EF Core 2.2 中的链式/嵌套属性

[英]How to access chained/nested property in EF Core 2.2

I have the following classes:我有以下课程:

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

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

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

And I have configured the owned entities as below in OnModelCreating method:我在OnModelCreating方法中配置了拥有的实体,如下所示:

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

The Problem问题

When I tried to save a null value in the owned entity like v.TurboV6.Core = null;当我尝试在拥有的实体中保存空值时,例如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. EF Core 不会将Vehicle.TurboV6.Core.Capacity空值保存为空,而是将先前的值保留在数据库中。 I assume this is caused by a problem in EF Core's change tracking.我认为这是由 EF Core 的更改跟踪中的问题引起的。

I tried to overcome this with :我试图用以下方法克服这个问题:

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

Take note that vContext is EntityEntry<Vehicle> type, not DbContext .请注意, vContextEntityEntry<Vehicle>类型,而不是DbContext

Similar to this question: Nested navigation properties using entity entry reference ,类似于这个问题: Nested navigation properties using entity entry reference

When I access the code below:当我访问以下代码时:

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

I got an error message saying我收到一条错误消息说

System.ArgumentException : The expression 'v => v.TurboV6.Core.Capacity' is not a valid property expression. System.ArgumentException :表达式“v => v.TurboV6.Core.Capacity”不是有效的属性表达式。 The expression should represent a simple property access: 't => t.MyProperty'.该表达式应该代表一个简单的属性访问:'t => t.MyProperty'。 (Parameter 'propertyAccessExpression') (参数'propertyAccessExpression')

I am using EF Core 2.2.6我正在使用 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?如果是,我该怎么做?

Thank you谢谢

TurboV6 and Core are reference navigation properties, so they must be accessed through Reference method. TurboV6Core参考导航属性,所以必须通过Reference方法访问。 The nested entity entry is accessible through TargetEntry property.嵌套实体条目可通过TargetEntry属性访问。 Repeat that until you get to the desired level entry on which you can use Property method.重复此操作,直到到达可以使用Property方法的所需级别条目。

Something like this:像这样的东西:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM