Open vflame opened 1 year ago
Note for triage: I am able to reproduce this. Looks like a potential issue with client evaluation in the final projection.
Is this the same issue?
public class DateRange
{
public DateTime Start {get;set;}
public DateTime End {get;set;}
// various datetime helper methods, properties
}
public class ContractPeriod
{
public int Id {get;set;}
public int ContractId {get;set;}
public DateRange Duration {get;set;} // etc...
public DateTime StartDate => Duration.Start;
}
// in dbContext
public override void Configure(EntityTypeBuilder<ContractPeriod> builder)
{
builder.OwnsOne(e => e.Duration);
}
public class PeriodCollection : ObservableCollection<ContractPeriod>
{
protected override void InsertItem(int index, ContractPeriod item)
{
if (item == null) return;
if (Items.Count != 0)
{
index = _binarySearch(item.StartDate);
}
base.InsertItem(index, item);
}
private int _binarySearch(DateTime date)
{
var lower = 0;
var upper = Items.Count - 1;
while (lower <= upper)
{
var middle = lower + (upper - lower) / 2;
var result = DateTime.Compare(date, Items[middle].StartDate);
if (result == 0)
return middle;
if (result < 0)
upper = middle - 1;
else
lower = middle + 1;
}
return lower;
}
}
public class Contract
{
public int Id {get;set;}
public string Buyer {get;set;}
public string Terms {get;set;} // etc...
private PeriodCollection _periods = new PeriodCollection();
public IEnumerable<ContractPeriod> Periods => _periods;
}
await AppData.Contracts
.Include(c => c.Periods)
.FirstAsync();
I will receive a System.NullReferenceException: 'Object reference not set to an instance of an object.'
at the InsertItem() of the custom collection. The ContractPeriod.Duration property is null. If I use a plain ObservableCollection or List, and do my sorting later, I get no such exception. It seems the Owned Entity is added to owner after the owner entity is added to the collection.
Please advise. I can open a separate issue if warranted. Thanks.
Jerry
File a bug
NullReferenceException thrown when entity hierarchy has owned entity when performing select projection. Not sure if related to: https://github.com/dotnet/efcore/issues/30107 and https://github.com/dotnet/efcore/issues/30373
Can provide repro project if needed
Include your code
Entities/Configs
Include provider and version information
EF Core version: 7.0.4 Database provider: Microsoft.EntityFrameworkCore.SqlServer & Npgsql Target framework: .NET 7.0 Operating system: WIN10 IDE: Visual Studio 2022