通过LINQ从sql中获取查询

时间:2013-12-26 11:57:02

标签: c# sql-server linq

原谅我的英语,我不是母语人士。

我想通过linq从SQL获取查询,但是在其中一个参考表的数据中保存了null,当零查询将返回时

LinqShoppingDataContext linqedit = new LinqShoppingDataContext();

var j = (from a in linqedit.Kharids
         join k in linqedit.KalaNames on a.KalaName_ref equals k.ID
         join n in linqedit.KindOfKharids on a.KindOfKharid_ref equals n.ID
         join g in linqedit.VahedeKharids on a.Vahedekharid_ref equals g.ID
         select new
         {
             a.ID,
             نام_کالا = k.Name,
             مقدار = a.mount.Value,
             واحد_خرید = g.Name,
             قیمت = a.Price,
             نوع_خرید = n.Name,
             نام_خریدار = a.NameKHaridar,
             تاریخ = a.Date.Date.Year + "/" + a.Date.Date.Month + "/" + a.Date.Date.Day
         }).ToList();

dataGridView1.DataSource = j;

这是我的查询,但保存在KindOfKharids表中的数据为空,因此查询返回零回答,如何解决我的问题?

2 个答案:

答案 0 :(得分:1)

var j = (from a in linqedit.Kharids    
     join k in linqedit.KalaNames on a.KalaName_ref equals k.ID   
      join n in linqedit.KindOfKharids on a.KindOfKharid_ref equals n.ID 
         into temptbl
         from m in temptbl.DefaultIfEmpty()
     join g in linqedit.VahedeKharids on a.Vahedekharid_ref equals g.ID
     select new
     {
         a.ID,
         نام_کالا = k.Name,
         مقدار = a.mount.Value,
         واحد_خرید = g.Name,
         قیمت = a.Price,
         نوع_خرید = n.Name,
         نام_خریدار = a.NameKHaridar,
         تاریخ = a.Date.Date.Year + "/" + a.Date.Date.Month + "/" + a.Date.Date.Day
     }).ToList();

dataGridView1.DataSource = j;

答案 1 :(得分:0)

这个怎么样?

var j = (from a in linqedit.Kharids
         join k in linqedit.KalaNames on a.KalaName_ref equals k.ID
         let n = linqedit.KindOfKharids.FirstOrDefault(n => a.KindOfKharid_ref == n.ID)
         let g = linqedit.VahedeKharids.FirstOrDefault(g => a.Vahedekharid_ref == g.ID)
         select new {
             a.ID,
             نام_کالا = k.Name,
             مقدار = a.mount.Value,
             واحد_خرید = g.Name,
             قیمت = a.Price,
             نوع_خرید = n.Name,
             نام_خریدار = a.NameKHaridar,
             تاریخ = a.Date.Date.Year + "/" + a.Date.Date.Month + "/" + a.Date.Date.Day
         }).ToList();

如果每个KhalaNames条目没有Kharids条目,则可以对نام_کالا值重复此模式。

此外,如果您正确设置了外键,您应该能够使用导航属性使这更简单:

var j = (from a in linqedit.Kharids
         select new {
             a.ID,
             نام_کالا = a.KalaName.Name,
             مقدار = a.mount.Value,
             واحد_خرید = a.VehedeKharid.Name,
             قیمت = a.Price,
             نوع_خرید = a.KindOfKharid.Name,
             نام_خریدار = a.NameKHaridar,
             تاریخ = a.Date.Date.Year + "/" + a.Date.Date.Month + "/" + a.Date.Date.Day
         }).ToList();