如何使用linq和EntityFramework获取对象的补充列表

时间:2016-05-31 16:04:40

标签: c# entity-framework linq

我有两种类型,一种是另一种类型:

<div onmouseover="PlaySound('mySound')" onClick="StopSound('mySound')">

我有一个名为 public class A { public int ID { get; set; } public string Name { get; set; } } public class B { public int ID { get; set; } public string Name { get; set; } public string Description { get; set; } } 的{​​{1}}由客户传递给我,我有一个EntityFramework DbContext,其中List<A>名为As。这两种类型可以在ID上匹配。

我想要获得的是DbSet<B>以外的所有Bs。你会怎么在Linq写的?我试图使用加入,但我似乎无法理解它。

在T-SQL中我会做这样的事情:

As

4 个答案:

答案 0 :(得分:3)

你可以这样做:

List<A> As = ... //This is a list in memory

//Get all ids of As
var A_ids = As.Select(x => x.ID).ToList();

//Get all ids that are in both As (memory) and TableB (database)
//We put them in a HashSet for performance reasons
var ids_in_tableB_also =
   new HashSet<int>(
       db.TableB
       .Where(x => A_ids.Contains(x.ID))
       .Select(x => x.ID));

//Get the A objects that are in `As` but of which IDs are not in ids_in_tableB_also
//This operation would have been slower if we haven't used the HashSet above
var rest_of_As = As.Where(x => !ids_in_tableB_also.Contains(x.ID)).ToList();

答案 1 :(得分:2)

嗯,你可以在LINQ中完全和SQL中一样:

var query = 
    from a in db.TableA
    join b in db.TableB on a.ID equals b.ID into aBs
    from b in aBs.DefaultIfEmpty()
    where b == null
    select a;

这是使用LINQ antijoin实现的标准left outer join模式。

编辑:如果A和B都是数据库表,则上述情况适用。如果A是内存列表而B是数据库表,则@Yacoub Massad answer是可行的方法。

答案 2 :(得分:1)

可能有点过于简单,但您是否考虑过.Except方法?

https://msdn.microsoft.com/en-us/library/bb300779(v=vs.100).aspx

List<A> as = ...
List<B> bs = ...
var idsYouWant = as.Select(a => a.Id).Except(bs.Select(b=>b.Id)).ToList();
var wholeObjectsYouWant = as.Where(a => idsYouWant.Contains(a.Id)); 

答案 3 :(得分:0)

试试此代码

dbContext.Set<A>()
    .Join(
        dbContext.Set<B>(),
        a => a.ID,
        b => b.ID,
        (a, b) => new
            {
                aID = a.ID,
                bID = b.ID,
                aName = a.Name,
                bName = b.Name,
                bDescription = b.Description
            });