我使用EF core:2.26,并且具有以下数据模型:
public interface IManeuverableAsset
{
OpenStateType? ManeuveredState { get; set; }
}
public interface IGeneratorManeuverableAsset : IManeuverableAsset
{
DateRange GeneratorInstallation { get; set; }
DateRange GeneratorRemoval { get; set; }
}
public class ManeuverableCabin : Entity<Guid>, IGeneratorManeuverableAsset
{
public Cabin Cabin { get; set; }
public List<ManeuverableCell> Cells { get; set; } = new List<ManeuverableCell>();
public DateRange GeneratorInstallation { get; set; }
public DateRange GeneratorRemoval { get; set; }
}
public class ManeuverableCell : Entity<Guid>, IManeuverableAsset
{
public Cell Cell { get; set; }
public List<ManeuverableCircuit> Circuits { get; set; } = new List<ManeuverableCircuit>();
public OpenStateType? ManeuveredState { get; set; }
}
public class ManeuverableCircuit : Entity<Guid>, IGeneratorManeuverableAsset
{
public Circuit Circuit { get; set; }
public OpenStateType? ManeuveredState { get; set; }
public DateRange GeneratorInstallation { get; set; }
public DateRange GeneratorRemoval { get; set; }
}
public class DateRange
{
public DateTime? Start { get; set; }
public DateTime? End { get; set; }
}
配置如下:
public class ManeuverableCabinConfiguration : IEntityTypeConfiguration<ManeuverableCabin>
{
public void Configure(EntityTypeBuilder<ManeuverableCabin> builder)
{
//builder.HasBaseType<ManeuverableAsset>();
builder.OwnsOne(entity => entity.GeneratorInstallation);
builder.OwnsOne(entity => entity.GeneratorRemoval);
builder.ToTable(nameof(ManeuverableCabin) + "s");
}
}
public class ManeuverableCellConfiguration : IEntityTypeConfiguration<ManeuverableCell>
{
public void Configure(EntityTypeBuilder<ManeuverableCell> builder)
{
builder.ToTable(nameof(ManeuverableCell) + "s");
}
}
public class ManeuverableCircuitConfiguration : IEntityTypeConfiguration<ManeuverableCircuit>
{
public void Configure(EntityTypeBuilder<ManeuverableCircuit> builder)
{
builder.OwnsOne(entity => entity.GeneratorInstallation);
builder.OwnsOne(entity => entity.GeneratorRemoval);
builder.ToTable(nameof(ManeuverableCircuit) + "s");
}
}
当我只保存一个ManeuverableCabin(没有单元/电路)时,它可以正常工作,但是,一旦我在DateRange中有一个没有值的ManeuvrableCircuit,我就会遇到此错误:
“ ManeuverableCabin”类型的实体正在共享表 实体类型为“ ManeuverableCabin” 'ManeuverableCabin.GeneratorInstallation#DateRange',但没有 此类型的实体具有与已标记为相同的键值 '添加'。考虑使用 'DbContextOptionsBuilder.EnableSensitiveDataLogging'查看密钥 值。'
我的日期范围从不为空,充其量只是默认的空实例。 这是我保存数据的方式:
public async Task SaveAsync(TEntity aggregate)
{
var existingAggregate = await _context.FindAsync<TEntity>(aggregate.Id);
if (existingAggregate == null)
await _context.AddAsync(aggregate).ConfigureAwait(false);
await _context.SaveChangesAsync().ConfigureAwait(false);
}
当我在await上放置一个断点时_context.AddAsync(aggregate).ConfigureAwait(false); 我的聚合看起来像这样:
但是当我跨步进入SaveChangesAsync时,我的对象发生了变化: 看到不同的帖子,我很确定问题是对象变为null,但是我不知道为什么... 当然,如果我在自己的日期范围内有价值,那一切都很好...
对此有任何想法吗? 抱歉,很长的帖子
谢谢!
答案 0 :(得分:0)
如Ivan Stoev所说,由于使用同一实例的自动映射器中的null替换,该对象被共享。