c# - 如何在 EF 中指定左连接?

标签 c# entity-framework orm

我的模型:

public partial class history_builds
{
    public int ID { get; set; }
    public int build { get; set; }
    public int br { get; set; }
    public int tag { get; set; }
    public string line { get; set; }
    public int rev { get; set; }
    public int user_ID { get; set; }
    public string distrib_path { get; set; }
    public string setup_path { get; set; }
    public System.DateTime build_date { get; set; }
    public string product { get; set; }
}

public partial class history_uploads
{
    public int ID { get; set; }
    public int ID_user { get; set; }
    public string Line { get; set; }
    public int Build { get; set; }
    public string Distrib { get; set; }
    public System.DateTime Time_upload { get; set; }
    public int Status { get; set; }
}

public partial class user
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int ID_group { get; set; }
}

上下文:

public DbSet<history_builds> history_builds { get; set; }
public DbSet<history_uploads> history_uploads { get; set; }
public DbSet<user> users { get; set; }

我尝试像这样进行左连接 Entity framework left join

var items = entities.history_builds
    .Join(
        entities.users.DefaultIfEmpty(),
        hb => hb.user_ID,
        u => u.ID,
        (hb, u) =>
            new {
                hb.distrib_path,
                hb.setup_path,
                hb.build_date,
                hb.build,
                User = (u == null ? String.Empty : u.Name),
                hb.rev
            }
    )
    .Join(entities.history_uploads.DefaultIfEmpty(),
        hb => hb.build,
        hu => hu.Build,
        (hb, hu) =>
            new HistoryBuidItem {
                Revision = hb.rev,
                Build = hb.build,
                DistribPath = hb.distrib_path,
                SetupPath = hb.setup_path,
                BuildDate = hb.build_date,
                User = hb.User,
                IsUpload = (hu == null ? true : false)
            }
    )
    .Where(x => ids.Contains(x.Revision))
    .ToList();

但它不起作用,EF 仍然发出内部连接 ​​sql 代码,有什么问题吗?

最佳答案

你应该使用 GroupJoin为此。

看例子:

var customers = db.Customer
                  .GroupJoin(db.SpecialCustomer, c => c.ID, g => g.CustomerId, (f, b) => new { f, b })
                  .SelectMany(z => z.b.DefaultIfEmpty(), (z, g) => new { z, g });

关于c# - 如何在 EF 中指定左连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12928803/

相关文章:

c# - 以相同的方式打乱两个列表

c# - 删除文件但不删除文件夹 C#

java - Hibernate - 通过用户名关系加密引用

c# - 在没有往返的情况下更新 Entity Framework 6

c# - 是否可以在 EntityCollection<T> 上实现 RemoveAll()?

python - 为 RethinkDB 测试 ORM

java - 基本的 Hibernate 缓存问题

c# - C#中的异常处理 : Multple Try/Catches vs. 一

c# - 如何使用 ValueConversions 检索 Entity Framework Core 的数据库模型

entity-framework - "...parameterless constructors and initializers are supported..."错误是什么意思?