I have a Location entity. It has a collection of opening hours and it should be stored as a JSON in the database.
public class Location
{
public Guid Id { get; set; }
public required string Name { get; set; }
public ICollection<OpeningHours> OpeningHours { get; set; } = new List<OpeningHours>();
}
public class OpeningHours
{
public DayOfWeek Day { get; set; }
public bool IsOpen24Hours { get; set; }
public ICollection<TimeInterval> Intervals { get; set; } = new List<TimeInterval>();
}
public class TimeInterval
{
public TimeOnly Start { get; set; }
public TimeOnly End { get; set; }
}
and below is my configuration
internal class LocationConfiguration : IEntityTypeConfiguration<Location>
{
public void Configure(EntityTypeBuilder<Location> builder)
{
builder.OwnsMany(
l => l.OpeningHours, ownedNavigationBuilder =>
{
ownedNavigationBuilder.ToJson();
ownedNavigationBuilder.OwnsMany(o => o.Intervals);
ownedNavigationBuilder.WithOwner();
});
}
}
No matter what when adding new migration it makes OpeningHours nullable. I want to make it non-nullable in the database
1条答案
按热度按时间qxsslcnc1#
You can try using the
.IsRequired()
method when configuring theOpeningHours
property.Make sure that the
Name
property in theLocation
class is marked as required if it is indeed a required field.Generate a new migration to apply the changes to your database:
Then, update the database:
Second implementation
Location
class, you can use the[Required]
attribute to specify that theOpeningHours
collection is required.DbContext
class, you can override theOnModelCreating
method and specify the configuration forOpeningHours
usingHasMany
andWithOne
.UseJson
extension method.