这是我的SQL查询:
select AU.Last_Name
From t_Batch B
left join (select distinct customer_id, subbatchtypeid
from t_allocationconfig where isactive='Y')
AA on AA.customer_id = B.Customer_id and
AA.SubBatchtypeid = B.SubBatchtypeid
left join t_batchallocation BA on BA.Batchid = B.Batchid
left join VW_users AU on AU.User_ID = BA.User_id;
我想将此SQL转换为Linq但我收到错误:
User_ID obecjt引用不是对象的实例
我该如何解决这个问题?
IList<Batch> result = new List<Batch>();
var batch = _batchservice.GetBatch().Where(r => r.ISACTIVE == "Y");
var batchallocation = _batchallocationservice.GetBatchAllocation();
var allocationconfig=_allocationconfigservice.GetAllocationConfig().Where(r=>r.ISACTIVE=="Y");
result = (from B in batch
join ac in (
from cl in allocationconfig where cl.ISACTIVE=="Y"
select new {cl.CUSTOMER_ID,cl.SUBBATCHTYPEID}
) on new {B.CUSTOMER_ID,B.SUBBATCHTYPEID}
equals new {ac.CUSTOMER_ID,ac.SUBBATCHTYPEID} into aac
from v in aac.DefaultIfEmpty(null)
join BA in batchallocation on B.BATCHID equals BA.BATCHID into x
from y in x.DefaultIfEmpty()
join AU in users on y.USER_ID equals AU.USER_ID into g
from h in g.DefaultIfEmpty()
select new Batch
{
AllocatedUserName=h.LAST_NAME
}).ToList();
答案 0 :(得分:2)
我想问题是x.DefaultIfEmpty返回一个空值,然后在连接访问users表(y.USER_ID)时导致错误。
DefaultIfEmpty子句有一个超载,它接受默认类型,例如
x.DefaultIfEmpty<BatchAllocation>(new BatchAllocation () { USER_ID = "-1", .... })
您可以尝试返回虚拟批处理分配默认值,其USER_ID属性为-1(假设没有用户ID可以为-1)这将返回h作为null,然后您可以过滤掉空值通过主查询中的位置。(其中h!= null&amp;&amp; h.LAST_NAME!= null)
以下示例 -
class Program
{
static void Main(string[] args)
{
LeftOuterJoinExample();
Console.ReadLine();
}
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Pet
{
public string Name { get; set; }
public Person Owner { get; set; }
}
public static void LeftOuterJoinExample()
{
Person magnus = new Person { FirstName = "Magnus", LastName = "Hedlund" };
Person terry = new Person { FirstName = "Terry", LastName = "Adams" };
Person charlotte = new Person { FirstName = "Charlotte", LastName = "Weiss" };
Person arlene = new Person { FirstName = "Arlene", LastName = "Huff" };
Pet barley = new Pet { Name = "Barley", Owner = terry };
Pet boots = new Pet { Name = "Boots", Owner = terry };
Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte };
Pet bluemoon = new Pet { Name = "Blue Moon", Owner = terry };
Pet daisy = new Pet { Name = "Daisy", Owner = magnus };
// Create two lists.
List<Person> people = new List<Person> { magnus, terry, charlotte, arlene };
List<Pet> pets = new List<Pet> { barley, boots, whiskers, bluemoon, daisy };
var query = from person in people
join pet in pets on person equals pet.Owner into gj
from subpet in gj.DefaultIfEmpty<Pet>(new Pet() { Name = "", Owner = null })
where subpet != null && subpet.Name != String.Empty
select new { person.FirstName, PetName = (subpet == null ? String.Empty : subpet.Name) };
foreach (var v in query)
{
Console.WriteLine("{0,-15}{1}", v.FirstName + ":", v.PetName);
}
}
}
答案 1 :(得分:0)
在使用之前,您需要检查y是否为空