使用include的EF核心连接

时间:2018-05-11 07:13:08

标签: entity-framework ef-core-2.0

我正在尝试使用Include加入相关数据,但我遇到了一些困难。我的模型如下

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)

然后我尝试在Device

中创建一个shadow属性

[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)   

但是它不起作用,因为它使用来自DeviceId的{​​{1}}和来自GBTObject的{​​{1}}来加入。将外键更改为Id会导致奇怪的命名错误(它将DeviceState命名为DeviceId,然后它会抱怨它不存在并且看起来像一个错误。)

我这样做错了吗?

0 个答案:

没有答案