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; } 
    } 
} 

私はDeviceNameのに基づいて特定のデバイスを取得できるようにしたいのですが、私はまた、特定の場所にあるすべてのデバイスを取得したいと思います。

私は、次の最初の質問のために働くだろうと思う:私はちょうど実行するために2番目のクエリを取得して苦労しています

var _Devices = DeviceContext.Devices.FirstOrDefault(d => d.DeviceName == "BLA"); 

。理想的には、出力はJSONにレンダリングされ、APIによって消費されます。

コード:

// 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); 
私は、次のコードを使用している場合、それは私に次のエラーを与える

{ 
    "Locations": { 
     "NYC": ["ABC", "123"], 
     "Boston": ["DEF", "456"], 
     "Chicago": ["GHI", "789"] 
    } 
} 

UPDATE

:私は、出力は次のようになりたいです

エラー:

Additional information: Self referencing loop detected for property 'DeviceLocation' with type 'Project.Models.DeviceLocation'. Path 'data[0].Device[0]'. 

答えて

1

次のように試すことができます。

注:IncludeでEager Loadingを使用してください。

using System.Data.Entity; 

var devicesList = DeviceContext.DeviceLocations.Where(d=>d.Location = "Your-Location-Name") 
           .Include(p => p.Devices) 
           .ToList(); 

更新:

var devicesList = DeviceContext.DeviceLocations 
           .Include(p => p.Devices) 
           .ToList(); 
+0

これは、あなたが自分のデバイスと場所のすべてを引っ張るだろうか、単一の場所を引っ張ってきますか? – tscrip

+0

**アップデート**をご覧ください – Sampath

関連する問題