首页 > 解决方案 > 复杂类型需要主键

问题描述

我有一个对象,其中包含具有另一个对象类型的属性,我想将其视为复杂类型。

public class Location : IModule
{
    public string Id { get; set; }
    public Coordinate Coordinate { get; set; }
}

[ComplexType]
public class Coordinate
{
    public string Latitude { get; set; }
    public string Longitude { get; set; }
}

在添加迁移时,我遇到了需要主键的问题(正是我想要防止的)。

实体类型Coordinate需要定义一个主键。

编辑

出于性能原因,我希望将属性存储为Coordinate_LatitudeCoordinate_Longitute不是引用另一个表。

标签: c#.netentity-frameworkprimary-key

解决方案


基于这个问题(如何在 Entity Framework Core 2/C# 中实现简单的“复杂类型”?),我找到了答案:拥有的实体类型可以解决问题。

public class Location : IModule
{
    public string Id { get; set; }
    public Coordinate Coordinate { get; set; }
}

[Owned]
public class Coordinate
{
    public string Latitude { get; set; }
    public string Longitude { get; set; }
}

这将创建一个包含属性IdCoordinate_Latitued、的表Coordinate_Longitude


推荐阅读