I’m currently working on a project using Entity Framework Core and I’ve encountered an issue with owned types. I have a structure similar to the following:
class MainEntity
{
public Guid Id { get; set; }
public virtual List<SecondEntity>? Seconds { get; set; }
}
class SecondEntity
{
public Guid Id { get; set; }
public Guid MainEntityId { get; set; }
public virtual MainEntity? MainEntity { get; set; }
public virtual List<ThirdEntity>? Third { get; set; }
public MyOwnedType MyOwnedType { get; set; } = null!;
}
class ThirdEntity
{
public Guid Id { get; set; }
public Guid SecondEntityId { get; set; }
public virtual SecondEntity? SecondEntity { get; set; }
public MyOwnedType MyOwnedType { get; set; } = null!;
}
public record MyOwnedType
{
public EMonth Month { get; init; }
public ushort Year { get; init; }
}
public enum EMonth
{
January = 1,
February = 2,
March = 3,
April = 4,
May = 5,
June = 6,
July = 7,
August = 8,
September = 9,
October = 10,
November = 11,
December = 12,
ExtraMonth = 13
}
In this structure, MyOwnedType is an owned type. When I create a new MainEntity and add it to the context using AddAsync, the MyOwnedType property in ThirdEntity is set to null, right after the AddAsync call. Note that the MyOwnedType property in SecondEntity is not set to null. This happens even though MyOwnedType has a value right before the AddAsync call.
Here’s the code where I add the entity:
public virtual Task AddAsync(MainEntity entity)
{
// ... some code here ...
return dbSet.AddAsync(entity).AsTask();
}
The MyOwnedType owned type is configured as follows:
builder.OwnsOne(o => o.Competencia,
sa =>
{
const string monthColumnName = "EMonth";
const string yearColumnName = "Year";
sa.Property(p => p.Month).HasColumnName(monthColumnName);
sa.Property(p => p.Year).HasColumnName(yearColumnName);
});
Notice that this problem happens even before any call to SaveChanges. Upon SaveChanges it indicates that the MyOwnedType property is required:
System.InvalidOperationException: 'Cannot save instance of 'ThirdEntity.MyOwnedType#MyOwnedType' because it is an owned entity without any reference to its owner. Owned entities can only be saved as part of an aggregate also including the owner entity.'
I’ve also tried adding the ThirdEntitys directly to the DbSet before adding the MainEntity. Upon adding the ThirdEntitys individually it doesn’t lose the MyOwnedType value, but after that, when the MainEntity is also added to the context, the MyOwnedType property in the ThirdEntitys are all set to null.