简体   繁体   English

在 EF Core 3.1 中定义可为空的拥有类型时,为什么会出现 NullReferenceException?

[英]Why do I get a NullReferenceException when defining a nullable owned type in EF Core 3.1?

I'm connecting to a Cosmos DB instance using Entity Framework Core 3.1.4.我正在使用 Entity Framework Core 3.1.4 连接到 Cosmos DB 实例。
I have a Broadcast class that contains a property of owned type Availability .我有一个广播class ,其中包含一个拥有类型的属性Availability
I don't want Availability to be mapped as an Entity.我不希望将可用性映射为实体。 Availabilities don't have Ids, nor should they be stored in their own containers.可用性没有 ID,也不应该存储在自己的容器中。 Availabilities are nullable .可用性是可以为空的 The classes look like:这些类看起来像:

public class Broadcast
{
    public string id {get; set;}
    public string Name { get; set; }
    public Availability Availability { get; set; }
}

[Owned]
public class Availability
{
    public DateTime? Start { get; set; }
    public DateTime? End { get; set; }
}

public class BroadcastContext : DbContext
{
    public DbSet<Broadcast> Broadcast{ get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Broadcast>().OwnsOne(e => e.Availability).WithOwner();
    }
}

So an item inside the Broadcast container in the DB should look like:因此,DB 中 Broadcast 容器内的项目应如下所示:

{
   id: "GUID",
   Name: "Foobar Broadcast",
   Availability: {
     Start: FooDate,
     End: BarDate
   }
}

When trying to Add a new Broadcast object with "Availability" set to null, this line: modelBuilder.Entity<Channel>().OwnsOne(e => e.Availabilities).WithOwner();当尝试添加新的广播object 并将“可用性”设置为 null 时,此行: modelBuilder.Entity<Channel>().OwnsOne(e => e.Availabilities).WithOwner(); throws the following exception:抛出以下异常:

System.NullReferenceException: 'Object reference not set to an instance of an object.' System.NullReferenceException:“对象引用未设置为 object 的实例。”

I understand that EF Core 3.0 supports nullable Owned Types.我了解 EF Core 3.0 支持可为空的拥有类型。
Am I missing something?我错过了什么吗? How can I sort this out?.我该如何解决这个问题?

When using navigation properties in EF, you want to use the virtual keyword.在 EF 中使用导航属性时,您希望使用 virtual 关键字。 This will allow EF to perform an override on the property.这将允许 EF 对该属性执行覆盖。

Try changing Broadcast to the following:尝试将广播更改为以下内容:

public class Broadcast
{
    public string id {get; set;}
    public string Name { get; set; }
    public virtual Availability Availability { get; set; } //added virtual keyword.
}

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

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