1
让我用前言来解释这个问题,我非常新到ASP.NET Core/EF Core。实体框架核心查询特定模型两个方向
我的模型是这样的:
namespace MyProject.Models
{
public class DeviceContext : DbContext
{
public DeviceContext(DbContextOptions<DeviceContext> options) : base(options) { }
public DbSet<Device> Devices { get; set; }
public DbSet<DeviceLocation> DeviceLocations { get; set; }
}
public class Device
{
public int Id { get; set; }
public string DeviceName { get; set; }
public string ServerName { get; set; }
public string MacAddress { get; set; }
public string LastUpdate { get; set; }
public string WiredIPAddress { get; set; }
public string WirelessIPAddress { get; set; }
public DeviceLocation DeviceLocation { get; set; }
}
public class DeviceLocation
{
public int Id { get; set; }
public string Location { get; set; }
public virtual ICollection<Device> Devices { get; set; }
}
}
我希望能够获取基于设备名称特定的设备,但我也想获取特定位置的所有设备。
我认为有以下将第一个问题的工作:
var _Devices = DeviceContext.Devices.FirstOrDefault(d => d.DeviceName == "BLA");
我只是有一个很难得到第二个查询运行。理想情况下,输出将呈现给JSON供API使用。我想输出是这个样子:
{
"Locations": {
"NYC": ["ABC", "123"],
"Boston": ["DEF", "456"],
"Chicago": ["GHI", "789"]
}
}
UPDATE
如果我使用下面的代码,它给我下面的错误:
代码:
// Grouping by ProfileName
var devices = DeviceContext.DeviceLocations.Include(n => n.Device).ToList();
var result = new { success = true, message = "Successfully fetched Devices", data = devices };
return JsonConvert.SerializeObject(result);
错误:
Additional information: Self referencing loop detected for property 'DeviceLocation' with type 'Project.Models.DeviceLocation'. Path 'data[0].Device[0]'.
这将拉动一个位置,你会怎么拉都与他们的设备的位置的? – tscrip
请参阅**更新** – Sampath