2014-12-24 49 views
1

我有一个IQueryable列表,它有5个字段。其中4个来自DB。 第五个字段必须使用联合声明(其他几个表中不包含引用该表的外键)从代码中分配。c#linq - 基于集合的操作

查询看起来像这样。

Profile对下列字段进行分类。

Id, Name, Username, Email, Product 

产品字段不在数据库中。必须使用以下查询在C#代码中进行填充。

var resultSet = (from a in Profiles 
        join _b_ in billingPeriodIncludes 
        on a.Id equals (int?) _b_._cbp.BundleId into b_ 
        from _b in b_.DefaultIfEmpty() 
        where a.Product != null 
        select new 
        { 
        a, 
        Product = (_b != null && _b._p != null) ? (_b._p) : a.Product 
        } 

该查询为我提供了配置文件和产品的组合。现在我遍历每个配置文件并将每个产品分配给其配置文件。

有人可以帮我做产品配置文件的直接集合分配?

这样的事情,(不工作)

var q1 = (from a in Profiles 
      join _b_ in billingPeriodIncludes 
      on a.Id equals (int?) _b_._cbp.BundleId into b_ 
      from _b in b_.DefaultIfEmpty() 
      select 
      //Assign products to the set. Query the set in a separate query. 
      a.Product = (_b != null && _b._p != null) ? (_b._p) : a.Product 
     ); 
var q2 = from _q2 in q1 select _q2; 
+1

这是不可能的。你这样做的方式是可以的。 – opewix

回答

3

试试这个: -

var resultSet = (from a in Profiles 
       join _b_ in billingPeriodIncludes 
       on a.Id equals (int?) _b_._cbp.BundleId into b_ 
       from _b in b_.DefaultIfEmpty() 
       where a.Product != null 
       select new Profiles 
       { 
        Id = a.Id, 
        Name = a.Name, 
        Username = a.Username, 
        Email = a.Email, 
        Product = (_b != null && _b._p != null) ? (_b._p) : a.Product 
       }; 

您可以直接绑定Profiles对象,而不是anonymous类型。

+0

虽然这可行,但Profiles类可能会增加列。如果添加了新列,它可能会在这里错过。 – Raghav

+0

@Raghav - 如果'Profiles'类会增长,它将在查询中可用,对吗?因为我们只加入'Profiles'类型。所以你说的是不正确的。 –

+0

你右拉胡尔。但是档案类被广泛使用。添加新列时,应在此处指定列的值。如果它错过了,它会导致默认列为空。查询是完美的,我只是在select部分寻找类似“select * from from”的东西。 – Raghav