Reputation: 193
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!
Upvotes: 11
Views: 3217
Reputation: 4246
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.
Upvotes: 1
Reputation: 473
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
Upvotes: 0