如何在 table 之间存在关系时使用 EF Core 访问另一个 table 中的列

How to access a column in an another table using EF Core while there is relationship between those tables

我正在使用 EF 核心与数据库建立连接。我的数据库是 SQLite。 我的属性是: 主题:

public class Topic
    {
        [Key]
        public int Id { get; set; }
        [Required]
        [DataType(DataType.Text)]
        [MaxLength(100)]
        public string Name { get; set; }

        public virtual List<SubTopic> SubTopics { get; set; }
    }

子主题:

public class SubTopic
    {
        [Key]
        public int Id { get; set; }
        [Required]
        [DataType(DataType.Text)]
        [MaxLength(100)]
        public string SubTopicname { get; set; }
        [Required]
        [DataType(DataType.Text)]
        [MaxLength(100)]
        public string Subject { get; set; }
        [Required]
        [DataType(DataType.Text)]
        [MaxLength(300)]
        public string ShortDiscription { get; set; }
        [Required]
        [DataType(DataType.Text)]
        public string Discription { get; set; }
        [Required]
        [DataType(DataType.Date)]
        public DateTime Date { get; set; }
        [Required]
        [DataType(DataType.Text)]
        public string Reference { get; set; }

        [ForeignKey("Name")]
        public virtual Topic Topic { get; set; }

    }

我想写一个查询在SubTopictable中找到一行Topicstable中对应的主题名称是Technology . 我试过这个: var subTopic = await _myContext.SubTopic.Include(x => x.Topic.Name == "Technology").FirstAsync();

但它不起作用。编写这样的查询的正确方法是什么?

Include 应该有一个指向导航的表达式 属性.

var subTopic = await _myContext.SubTopic
    .Include(st => st.Topic)
    .Where(x => x.Topic.Name == "Technology")
    .FirstOrDefaultAsync();

从 .NET 5 开始,EF Core 也支持过滤包含:

var subTopic = await _myContext.SubTopic
    .Include(st => st.Topic
        .Where(t => t.Name == "Technology")
    )
    .FirstOrDefaultAsync();

但在您的情况下,您可能甚至不需要包含导航 属性:

var subTopic = await _myContext.SubTopic
    //.Include(st => st.Topic)
    .Where(st => st.Topic.Name == "Technology")
    .FirstOrDefaultAsync();

虽然我读到这可能会降低大型数据集的性能