How can I create a Required Owned Type with Entity Framework Core 3.0
Asked Answered
N

2

11

I'm struggling creating a non-nullable/required Owned Type with Entity Framework Core. I'm using EF Core 3.0 against PostgreSQL database.

My value object:

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

        public string Name { get; set; }
    }

My entity:

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

        public virtual PersonName FullName { get; set; }
    }

My entity configuration:

    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");
        });
    }

The value type property is successfully persisted into the 'Person' table in the database but the column apears to be nullable despite that I'm using 'IsRequired()' method.

Thanks a lot!

Nikaniki answered 10/12, 2019 at 21:38 Comment(1)
I'm having the same issue with EF Core 3.1 and I haven't been able to find a solution. I could just manually change the migration script and set the nullable value to false, but that's a dirty solution.Rex
B
1

You can do this:

builder.OwnsOne(x => x.FullName );
builder.Navigation(x => x.FullName ).IsRequired();                

Or simply via attribute:

[Required]
public virtual PersonName FullName { get; set; }

The source for this are the EF Core 6 What's New docs, but I think it should already work starting from EF Core 5.

Boiler answered 13/9, 2023 at 13:15 Comment(1)
This also works with EF Core 7Ezraezri
I
0

So after some digging into the same problem the fix appears to be upgrade to ef core 5 (when its released) or manually edit the migrations. See the following github issue for discussion:

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

Introjection answered 1/9, 2020 at 5:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.