It is weird that the reference object is null even when corresponding refernce record actually exists. Here are the details.
// Model
public class ItemSoldPrice
{
public int Id { get; set; }
public int? ItemId { get; set; }
...
public ItemForSale Item { get; set; }
}
public class ItemForSale
{
[Key]
[Column("PKID")]
public int LeadID { get; set; }
//some other simple properties
}
//OnModelCreating setting
modelBuilder.Entity<ItemSoldPrice>()
.HasOne(t => t.Item)
.WithOne()
.HasForeignKey<ItemSoldPrice>(t => t.ItemId );
//Query
public IList<ItemSoldPrice> GetItems(int amount)
{
var list = DbContext.ItemSoldPrices
.Where(xxx && t.ItemId != null && t.Item != null)
.Include(t => t.Item)
.OrderByDescending(t => t.xxx).Take(amount).ToList();
return list;
}
Table ItemSoldPrice.
Id | ItemId | Other Columns |
---|---|---|
67691 | 93686 | xxxxxxxx |
When ItemSoldPrice.Id=67691
, there is acutally a corresponding item in database with ItemId=93686
, but returned ItemSoldPrice.ItemId and ItemSoldPrice.Item are both null. Why does it happen?
The werid thing is if I don’t include reference object in query, ItemSoldPrice.ItemId can be filled with correct value.
var list = DbContext.ItemSoldPrices
.Where(xxx && t.ItemId != null && t.Item != null)
.OrderByDescending(t => t.xxx).Take(amount).ToList();
Why .Include(t => t.Item)
lead to null reference?
4
You should define your Entity model more clearly, like this:
public class ItemSoldPrice
{
public int Id { get; set; }
public ItemForSale ItemForSale { get; set; }
public int ItemForSaleId { get; set; }
}
And
public class ItemForSale
{
public int Id { get; set; }
public ItemSoldPrice ItemSoldPrice { get; set; }
public int ItemSoldPriceId { get; set; }
}
Now EF can figure out the relationship itself. No need for any other ModelBuilder Settings.
2