We store translated texts in the database. These text resources are joined to products (called positions) or other entities. This worked good so far, as long as the texts were mandatory.
We have positions where the name is mandatory and can be found in several languages in the TextResources table.
The EF configuration looks like that:
public class Position
{
public Guid Id { get; set; }
public Guid NameResourceId { get; set; }
public List<TextResource> Names { get; set; } = new(); // works fine
public Guid? RemarkResourceId { get; set; }
public List<TextResource> Remarks { get; set; } = new(); // exception
}
public void Configure(EntityTypeBuilder<Position> builder)
{
builder.ToTable("Position", "Product");
builder.HasKey(p => p.Id);
builder.Property(p => p.Id).HasColumnName("Id").IsRequired();
builder.Property(p => p.NameResourceId).HasColumnName("NameResourceId").IsRequired();
builder.HasMany(p => p.Names).WithOne().HasPrincipalKey(a => a.NameResourceId).HasForeignKey(r => r.ResourceId);
builder.Property(p => p.RemarkResourceId).HasColumnName("RemarkResourceId");
builder.HasMany(p => p.Remarks).WithOne().HasPrincipalKey(a => a.RemarkResourceId).HasForeignKey(r => r.ResourceId);
}
I want to load all Remarks with the same ResourceId as in the RemarkResourceId if any.
But when I try to load the data, I get an ArgumentNullException with message Value cannot be null. (Parameter 'key').
If I define the RemarkResourceId as not nullable and add the IsRequired() in configuration, then it works.
How do I configure an optional navigation property?
We use .Net 6.0 by the way.
