I am trying to join related data using Include
but I am having some difficulties. My models are the following
public partial class GBTObject
{
public uint Id { get; set; }
public uint OrganizationId { get; set; }
public string Name { get; set; }
public virtual Device Device { get; set; }
public uint? DeviceId { get; set; }
}
public partial class Device
{
public uint Id { get; set; }
public uint OrganizationId { get; set; }
public string UUID { get; set; }
public bool? Enabled { get; set; }
}
public partial class DeviceState
{
public uint Id { get; set; }
public uint OrganizationId { get; set; }
public uint DeviceId { get; set; }
public string State { get; set; }
public DateTime? Timestamp { get; set; }
public byte? Event { get; set; }
public ulong TotalDistance { get; set; }
public string UserAgent { get; set; }
}
var data = _context.GBTObject
.Where(x => x.DeviceId != null && x.OrganizationId == _user.OrganizationId)
.Include(x => x.Device)
.Include(x => x.State)
Then I tried to create a shadow property inside Device
[ForeignKey("Id")]
public virtual DeviceState State{ get; set; }
var data = _context.GBTObject
.Where(x => x.DeviceId != null && x.OrganizationId == _user.OrganizationId)
.Include(x => x.Device)
.ThenInclude(x => x.State)
But it doesn't work cause the it joins using the the DeviceId
from GBTObject
with Id
from DeviceState
. Changing the foreign key to DeviceId
results in weird naming errors(it names the GBTObject.DeviceId
to GBTObject.DeviceId1
and then it complains that it doesn't exist and looks like a bug).
Am I doing this wrong?