c# - 用于 3 个表连接的 Entity Framework 7 Lambda 表达式

标签 c# asp.net-mvc entity-framework

我正在尝试构建一个 API,它将返回服务器的所有数据。一个服务器可以有多个端点,它们存储在具有多对多关系的单独表中。

我有 3 张 table :

  • Servers 表包含所有服务器详细信息
  • Applications 包含应用程序名称的表
  • application_endpoint 表,包含表 ServersApplications 的外键

这是我的数据库模型:

enter image description here

这是我的模型:

public class Servers
{
        public int id { get; set; }
        public string server_name { get; set; }
        public string alias { get; set; }
        public string ip_address { get; set; }
        public Status status { get; set; }
        public virtual ICollection<Application_endpoints> endpoint { get; set; }
}

public class Application_endpoints
{
        public int id { get; set; }
        public int? server_id { get; set; }
        [ForeignKey("server_id")]
        public Servers server { get; set; }
        public int? application_id { get; set; }
        [ForeignKey("application_id")]
        public Applications application { get; set; }
}

public class Applications
{
        public int id { get; set; }
        public string app_name { get; set; }
}

public class ServerDbContext : DbContext
{
        public DbSet<Applications> Applications { get; set; }
        public DbSet<Application_endpoints> Application_endpoints { get; set; }
        public DbSet<Servers> Servers { get; set; }
}

在我的 Api Controller 中,我创建了 HttpGet 方法,该方法将查询数据库并返回每个服务器的数据。这是简单的 GET API:

private ServerDbContext _context;

public ServersController (ServerDbContext context)
{
    _context = context;
}

// GET: api/values
[HttpGet]
public JsonResult Get()
{
    var servers = _context.Servers
        .Include(endpoint => endpoint.endpoint)
        .ToList();
    return Json(servers);
}

现在,当我发出 get 请求时,我从数据库获取数据,但是下面 JSON 中的 application 对象返回 null。我试图弄清楚如何在上面的查询中添加左连接,以便我可以从应用程序表中获取应用程序名称。

{
  "id": 6,
  "server_name": "server1",
  "alias": "",
  "ip_address": "192.168.1.7",
  "endpoint": [
    {
      "id": 23,
      "server_id": 6,
      "application_id": 10,
      "application": null
    }
  ]
}

非常感谢任何帮助。 :)

最佳答案

致所有人,

感谢您引导我走上正确的道路。我快速进行了 google 搜索,发现 EF7 中的语法已发生变化。以下对我有用:)

var servers = _context.Servers
            .Include(e => e.endpoint).ThenInclude(a => a.application)
            .ToList();

关于c# - 用于 3 个表连接的 Entity Framework 7 Lambda 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35384124/

相关文章:

c# - Linq lambda 实体,不包含定义

c# - Id 在 Action 方法中变为 Null

entity-framework - Entity Framework 5 : How to Outer Join Table Valued Function

c# - 如何在 Dynamics CRM 2011 中获取每个帐户的事件?

c# - 有没有办法让字符串达到年份值?

c# - 如何让 silverlight 从 MySQL 获取数据

c# - ViewBag 中的 System.Random 不显示为字符串?

asp.net-mvc - 在 Azure 中启用自定义错误

entity-framework - 如何删除两个实体之间的关系

c# - 方法返回非空值后抛出空引用异常