SELECT
Products.id, [Products].Name
FROM
[Products]
LEFT JOIN
[AvailableProducts] ON [AvailableProducts].IdProduct = [Products].Id
AND [AvailableProducts].IdUser = 'daa8ee71-f1d7-4b41-aa1c-464ae730dd63'
WHERE
([AvailableProducts].IdProduct IS NULL)
我正试图解决这个Linq代码的问题:
public void DataBindGridProducts(string idUser)
{
List<Product> data = new List<Product>();
var con = from test in db.AvailableProducts
join product in db.Products on new { test.IdProduct, test.IdUser} equals new { product.Id, idUser}
select new
{
surname = product.Name,
};
grdConnectedProduct.DataSource = data;
grdConnectedProduct.DataBind();
}
但这不正确。请帮帮我!
答案 0 :(得分:2)
我修好了它:
var o = (from p in db.Products
join p2 in db.AvailableProducts on new { f1 = (int)p.Id, f2 = idUser } equals new { f1 = (int)p2.IdProduct, f2 = p2.IdUser }
into temp
from x in temp.DefaultIfEmpty()
where x.IdProduct == null
select new { f1 = p.Name});
答案 1 :(得分:0)
public void DataBindGridProducts(string idUser)
{
List<Product> data = new List<Product>();
var con = from product in db.Products
join ap in db.AvailableProducts on new { x= (int)product.Id, y = product.idUser } equals new { x = (int)ap.IdProduct, y = ap.IdUser }
where product.IdProduct = null
select new
{
surname = product.Name,
};
grdConnectedProduct.DataSource = data;
grdConnectedProduct.DataBind();
}
您使用 lambda表达式。
我认为以下代码应该有效
public void DataBindGridProducts(string idUser)
{
List<Product> data = new List<Product>();
var con = db.Products.Join(db.AvailableProducts,
product => new{(int)product.Id, product.idUser},
ap => new { (int)ap.IdProduct, ap.IdUser },
(product, ap) => product)
.Where(product => product.IdProduct = null)
.Select(x => x new
{
surname = x.Name,
})
.ToList();
grdConnectedProduct.DataSource = data;
grdConnectedProduct.DataBind();
}
答案 2 :(得分:0)
你的t-sql查询等于这个查询:
SELECT
[product].[Id],
[product].[Name]
FROM
[Products] [product]
LEFT JOIN (
SELECT
[j].[IdProduct],
[j].[IdUser]
FROM
[AvailableProducts] [j]
WHERE
[j].[IdUser] = N'daa8ee71-f1d7-4b41-aa1c-464ae730dd63'
) [t1] ON [product].[Id] = [t1].[IdProduct]
WHERE
[t1].[IdProduct] IS NULL AND [t1].[IdUser] IS NULL
Linq查询有这样的观点:
var availableProductsQuery = from ap in db.AvailableProducts
where ap.IdUser == "daa8ee71-f1d7-4b41-aa1c-464ae730dd63"
select ap;
var con = from product in db.Products.AsQueryable()
join test in availableProductsQuery
on product.Id equals test.IdProduct into j
from ap in j.DefaultIfEmpty()
where ap == null
select product;