如何使用 Entity Framework Core 3.0 创建所需的拥有类型

sup*_*rio 7 c# postgresql value-objects entity-framework-core owned-types

我正在努力使用 Entity Framework Core 创建一个不可为空/必需的拥有类型。我正在对 PostgreSQL 数据库使用 EF Core 3.0。

我的价值对象:

    public class PersonName
    {
        public PersonName(string name)
        {
            this.Name = name;
        }

        public string Name { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

我的实体:

    public class Person
    {
        public int Id { get; set; }

        public virtual PersonName FullName { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

我的实体配置:

    public void Configure(EntityTypeBuilder<Person> builder)
    {
        builder.ToTable(nameof(Person));
        builder.HasKey(person => person.Id);

        builder.OwnsOne(person => person.FullName, personName =>
        {
           personName.Property(pn => pn.Name).IsRequired().HasColumnName("FullName");
        });
    }
Run Code Online (Sandbox Code Playgroud)

值类型属性已成功保存到数据库中的“Person”表中,但尽管我使用的是“IsRequired()”方法,但该列仍然可以为空。

非常感谢!

小智 0

因此,在深入研究同一问题后,修复似乎是升级到 ef core 5(发布后)或手动编辑迁移。请参阅以下 github 问题进行讨论:

https://github.com/dotnet/efcore/issues/12100