首页 > 解决方案 > 将 Entity Framework Core 与 Cosmos Db 一起使用时映射无密钥类型

问题描述

我有以下课程:

[Keyless]
public class SimpleTimeSpan
{
    public int Days { get; set; }
    public int Hours { get; set; }
    public int Minutes { get; set; }
}

我在这样的实体类中使用它:

public class MyEntity
{
    public Guid Id { get; set; }
    public string SomeProperty { get; set; }
    public SimpleTimeStapn Cutoff { get; set; }
}

我使用 Cosmos db 作为数据库并使用包 Microsoft.EntityFrameworkCore.Cosmos 5.0.x。

保存到数据库时,我希望有这样的实体

{
  "Id": "xxxx-yyyy-zzzz",
  "SomeProperty": "my value",
  "Cutoff": {
    "Days": 1,
    "Hours": 5,
    "Minutes": 20
  }
}

对于此属性,我收到此错误:

InvalidOperationException:无法确定“SimpleTimeSpan”类型的导航“MyEntity.Cutoff”表示的关系

如何映射此属性?

标签: entity-framework-coreazure-cosmosdb

解决方案


正如@Danyliv在评论部分提到的,使用Owned 实体类型允许您对只能出现在其他实体类型的导航属性上的实体类型进行建模。包含拥有实体类型的实体是其所有者。

您的课程将如下所示:

[Owned]
public class SimpleTimeSpan
{
    public int Days { get; set; }
    public int Hours { get; set; }
    public int Minutes { get; set; }
}

推荐阅读