EF核心-可为空的复杂属性

时间:2019-03-06 08:56:11

标签: c# asp.net-core entity-framework-core

我希望能够创建一个Order对象,而无需在创建时(以db为单位)定义SomeOptionalType

数据库中的afaik必须为空的foregin键

带有Postgre sql驱动程序的.NET Core 2.1 / EF Core

public class Order
{
    [ForeignKey("SomeOptionalTypeId")]
    public Guid SomeOptionalTypeId { get; set; }
    public SomeType? SomeOptionalType { get; set; }
}

public class SomeType
{
    public Guid Id { get; set; } = Guid.NewGuid();
}

我该如何实现?

1 个答案:

答案 0 :(得分:2)

如果SomeType? SomeOptionalType是可选的,可以是null,那么Guid SomeOptionalTypeId也可以是null

Guid更改为Guid?

[ForeignKey("SomeOptionalTypeId")]
public Guid? SomeOptionalTypeId { get; set; }