EF.Core querying related data

asp.net-core c# entity-framework-core

Question

I had some trouble with getting the 1to1 relations working in EF.Core,

I have these models:

public class IncomingData
{
    [Key]
    [Required]
    public int Id { get; set; }

    ...

    public History History { get; set; }
}

public class History
{
    [Key]
    public int Id { get; set; }

    ...

    [ForeignKey("IncomingDataId")]
    public IncomingData IncomingData { get; set; }
}

And the History Database seems to correctly store the ForeignKey as IncommingDataId

enter image description here

But when I execute the following code into my controller

var histories = _db.Histories.Where(x => x.IMEI == device.IMEI).OrderByDescending(x => x.Timestamp);

histories.IncomingData is always null

So I had to do some hackish workaround to have the histories contain IncomingData

foreach (var h in histories) {
    var incomingDataRecord = _db.IncomingData.FirstOrDefault(x => x.History == h);
}

I believe I'm doing something wrong somewhere :) If for information is needed, I'll add it

1
1
4/6/2018 4:33:44 PM

Accepted Answer

You don't Include the related entity object.

https://docs.microsoft.com/en-us/ef/core/querying/related-data

var histories = _db.Histories
    .Where(x => x.IMEI == device.IMEI)
    .OrderByDescending(x => x.Timestamp)
    .Include(x => x.IncomingData);
1
3/23/2018 5:48:16 PM

Popular Answer

Not 100% certain without running it, but I think you are looking for this...

public class IncomingData
{
[Key]
[Required]
public int Id { get; set; }

...

public History History { get; set; }
}

public class History
{
[Key]
public int Id { get; set; }

...

[InverseProperty("Id")]
public IncomingData IncomingData { get; set; }
}

and you retrieve it with...

var histories = _db.Histories.Where(x => x.IMEI == device.IMEI).Include("IncomingData").OrderByDescending(x => x.Timestamp);

assuming IMEI and Timestamp are properties of History



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow