微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

实体框架在外键条件下产生左连接

如何解决实体框架在外键条件下产生左连接

我有 2 个模型:

public class User
{
    public int Id { get; set; }

    [required] 
    [MaxLength(50)]
    public string Email { get; set; }

    [required] 
    [MaxLength(100)] 
    public string Password { get; set; }
}

public class Questionnaire
{
    public int Id { get; set; }

    [required] 
    [MaxLength(500)] 
    public string Title { get; set; }

    public User User { get; set; }
}

我想用这个查询来检索某个用户的所有问卷:

List<Questionnaire> questionnaires = this._dbContext.Questionnaires.Where(a => a.User.Id == 1).ToList();

它可以工作,但实体框架会生成这个 sql 查询

SELECT `q`.`Id`,`q`.`Title`,`q`.`UserId`
FROM `Questionnaires` AS `q`
     LEFT JOIN `Users` AS `u` ON `q`.`UserId` = `u`.`Id`
WHERE `u`.`Id` = 1;

在我看来,左连接是不必要的。请问有什么解决方法可以避免这种左连接吗?提前致谢。

解决方法

您需要手动公开 UserId 上的 Questionnaire 属性:

public class Questionnaire
{
    public int Id { get; set; }

    [Required] 
    [MaxLength(500)] 
    public string Title { get; set; }

    public int UserId { get; set; }
    public User User { get; set; }
}

并在查询中使用它而不是 a.User.Id

var questionnaires = this._dbContext.Questionnaires
    .Where(a => a.UserId == 1) // use UserId instead of User.Id
    .ToList(); 
,

更多信息:

If you choose not to explicitly include a foreign key property in the dependant end of the relationship,EF Core will create a shadow property using the pattern Id。如果您查看 Questionnaire 数据库表,UserId 列存在并且它已由 EF 核心创建为影子外键。

当您在 where 子句 User 中引用 _dbContext.Questionnaires.Where(a => a.User.Id == 1) 时,EF Core 将 linq 查询转换为 TSQL 左连接。

你也可以使用 shadow 属性来定义外键:

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<Questionnaire>()
        .Property<int>("UserId");

    builder.Entity<Questionnaire>()
        .HasOne(e => e.User)
        .WithMany()
        .HasForeignKey("UserId")
        .OnDelete(DeleteBehavior.SetNull);
}

现在左连接将被内连接替换:

SELECT [q].[Id],[q].[Title],[q].[UserId]
      FROM [Questionnaires] AS [q]
      INNER JOIN [Users] AS [c] ON [q].[UserId] = [c].[Id]
      WHERE [c].[Id] = 1

为了避免不必要的加入,正如@Guru Stron 所说,您需要在 UserId 类上公开 Questionnaire 属性。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?