【问题标题】:How to query a SQL database using C# based on a foreign key match如何使用 C# 基于外键匹配查询 SQL 数据库
【发布时间】:2020-07-19 18:52:15
【问题描述】:

我的数据库有以下实体类:

[Table("Results")]
    public class ResultsEntity
    {
        [Key]
        public Guid Id { get; set; }
        public Guid ComponentId { get; set; }
        [ForeignKey("ComponentId")]
        public ComponentEntity Component { get; set; }
        public Status Status { get; set; }
        public decimal Value { get; set; }
        public string Units { get; set; }
        public DateTime CreatedAt { get; set; }
    }

[Table("Components")]
    public class ComponentEntity
    {
        [Key]
        public Guid Id { get; set; }
        public string Title { get; set; }
        public string IconCode { get; set; }
    }

我想查询我的 Results 表并获取结果信息以及 ComponentEntity Title(来自 Components 表)。它们通过ComponentId Guid 的外键连接。这是我第一次使用 C# 查询 SQL 数据库,我正在努力寻找正确的语法。到目前为止,我的尝试如下:

IQueryable<ResultsEntity> resultQuery =
                from results in _dbContext.Results
                select results;


            foreach (ResultsEntity result in resultQuery)
            {
                var resultData = new ResultData
                {
                    Id = result.Id,
                    Status = result.Status,
                    Primary = result.Value,
                    Units = result.Units,
                    // How can I get the title of the component here? 
                };
            }
        }

谁能指出我正确的方向?谢谢

【问题讨论】:

    标签: c# sql database linq


    【解决方案1】:

    试试

    _dbContext.Results.Include(e => e.Component).Select(item =>
            new ResultData
                {
                    Id = item.Id,
                    Status = item.Status,
                    Primary = item.Value,
                    Units = item.Units,
                    Title = item.Component.Title
                };);
    

    您在此处包含 Component 以使用 DB 中的值填充它。之后,您可以使用 ResultsEntity 中的 Component 字段来获取必要的值。

    【讨论】:

      【解决方案2】:

      您可以使用以下 linq 查询加入它

      from results in _dbContext.Results
                  .Include(r => r.ComponentEntity)
              select results;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-21
        相关资源
        最近更新 更多