我正在尝试访问Register
上的RegisterCountLog
导航属性。由于某种原因,它始终为空。因此,当我尝试访问RegisterName时,它始终为null。
public IQueryable<RegisterCountLog> GetCountsForDevice(long deviceSerial)
{
return this.ServiceCollection.GetAll(c => c.Register)
.Where(c => c.DeviceSerial == deviceSerial).AsNoTracking();
}
请注意,ServiceCollection.GetAll()
将(或应该)包含Register
。该特定位queryableLogs
之后的查询是
SELECT
[Extent2].[Contribution] AS [Contribution],
[Extent1].[DeviceSerial] AS [DeviceSerial],
[Extent1].[LogEntryID] AS [LogEntryID],
[Extent1].[RegisterId] AS [RegisterId],
[Extent1].[Value] AS [Value],
[Extent1].[Timestamp] AS [Timestamp],
[Extent2].[RegisterId] AS [RegisterId1],
[Extent2].[DeviceSerial] AS [DeviceSerial1],
[Extent2].[RegisterName] AS [RegisterName],
[Extent2].[ZoneEntrance_ZoneEntranceID] AS [ZoneEntrance_ZoneEntranceID]
FROM [dbo].[RegisterCountLogs] AS [Extent1]
INNER JOIN [dbo].[Registers] AS [Extent2]
ON ([Extent1].[RegisterId] = [Extent2].[DeviceSerial])
AND ([Extent1].[DeviceSerial] = [Extent2].[RegisterId])
它的用法如下:
var queryableLogs = countLogService.GetCountsForDevice(serialNumber);
var groupedLogs= gLogs
.Select(r => new Register
{
RegisterId = r.FirstOrDefault().RegisterId,
RegisterName = r.FirstOrDefault().Register.RegisterName, // Here!
DeviceSerial = r.FirstOrDefault().DeviceSerial,
CountLogs = r.GroupBy(rc =>
new {Day = SqlFunctions
.DatePart("dy", rc.Timestamp)})
.Select(rl => new RegisterCountLog()
{
Value = rl.to FirstOrDefault().Value,
Timestamp = rl.FirstOrDefault()
.Timestamp,
})
.OrderByDescending(l => l.Timestamp)
.ToList()
})
.Where(r=>r.CountLogs.Count() > 0)
.OrderByDescending(r => r.RegisterId)
.ToList();
除RegisterName
始终为空之外,一切都很完美。如果我查看查询Register
也是null。为什么不加载?
以下是EF课程
public class RegisterCountLog
{
[Key, Column(Order = 1)]
[ForeignKey("Register")]
public long DeviceSerial { get; set; }
[Key, Column(Order = 2)]
public long LogEntryID { get; set; }
[Key, Column(Order = 3)]
[ForeignKey("Register")]
public long RegisterId { get; set; }
public long Value { get; set; }
public DateTime Timestamp { get; set; }
public Register Register { get; set; }
}
public class Register
{
public enum ContributionType
{
FlowIn,
FlowOut
}
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Key, Column(Order = 1)]
public long RegisterId { get; set; }
[Key]
[ForeignKey("Device"), Column(Order = 2)]
public long DeviceSerial { get; set; }
[StringLength(50)]
public string RegisterName { get; set; }
public ContributionType Contribution { get; set; }
public virtual Device Device { get; set; }
}
答案 0 :(得分:0)
您可能正在使用预先加载,但必须指定.Include(x => x.Register)
或.Include("Register")
,具体取决于您的EF版本
如果你给变量命名很好,可能会有另一个问题(对于分组的东西,急切加载并不是很好)。一种方法是在选择内容之前枚举查询(列表)。 (如果没有性能问题)
编辑:当我读到你之前的评论时,我真的认为是按问题分组(通过更改你的linq结构分组并且包括不工作的任何人)方法是:
var groupedPersons = db.Appointments
.Include_Service()
.Include_Location()
.Include_Room()
.IncludeEhr_Patient()
.IncludeEhr_Person()
.IncludeEhr_Personal()
.ToList() // see that i enumerate before i group by
.GroupBy(x => x.PersonId).Select()[.ToList()]