我的数据库中有3个表。公司,产品和主管。以下是我的字段。
SELECT [Id]
,[BuySellTypeId]
,[ProductName]
,[Keywords]
,[CategoryId] // categoryid
,[SubCategoryId]
,[Description]
,[ProductImagePath]
,[CreationDate]
,[ExpiryDate]
,[CompanyId] // company id
,[ShortDescription]
,[IsExpired]
,[IsActive]
FROM [BuySell]
SELECT
Id,
Name,
Description,
ImagePath,
CompanyId, //company id
Keywords,
CategoryId, // categoryid
SubCategoryId,
PostedDate,
ExpiryDate,
ShortDescription,
IsActive,
IsExpired
FROM Products
我还有一个表“公司”,其引用如上表所示。我的要求是取出上表中的所有公司,产品和BuySell在同一类别。
例如,如果我想看到CategoryId = 15的所有公司,那么它将从buysell和products表中提取categoryid = 15的所有公司。显然会有冗余,所以我会使用Distinct()
来提取不同的项目。
My Linq2Sql Biz图层方法
/// <summary>
/// Returns all companies by category id that exists in Lead and Products
///table
/// </summary>
/// <param name="categoryId">category id as integer</param>
/// <param name="take">records to take</param>
/// <param name="skip">records to skip</param>
/// <returns>List of companies</returns>
public static IList GetCompaniesByCategory(int categoryId, int take, int skip)
{
return (from c in Context.Companies
join bs in Context.BuySells on c.CompanyId equals bs.CompanyId
join p in Context.Products on c.CompanyId equals p.CompanyId
where bs.CategoryId == categoryId || p.CategoryId==categoryId
select new
{
c.CompanyId,
c.CompanyName,
c.Country.Flag,
c.Profile,
c.IsUsingSMSNotifications,
c.IsVerified,
c.MembershipType,
c.RegistrationDate, c.ShortProfile,
}).Skip(skip).Take(take).Distinct().ToList();
}
但上面的代码返回0项。当我设计它的sql时,见下文,
SELECT dbo.Company.CompanyId, dbo.Company.CompanyName, dbo.Company.Name, dbo.Company.IsVerified, dbo.Company.IsUsingSMSNotifications,
dbo.Company.CompanyLogo, dbo.Company.RegistrationDate, dbo.Company.Profile
FROM dbo.BuySell INNER JOIN
dbo.Company ON dbo.BuySell.CompanyId = dbo.Company.CompanyId LEFT OUTER JOIN
dbo.Products ON dbo.Company.CompanyId = dbo.Products.CompanyId
WHERE (dbo.BuySell.CategoryId = 1) AND (dbo.Products.CategoryId = 1)
我可以从BuySell获得该公司,但不能从Product获得。所以请帮助我。 I need the LINQ equivalent statement. To replace the above cs code.
答案 0 :(得分:0)
如果这些表之间有任何关系,查询可能会更简单
return (from c in Context.Companies
where c.BuySells.Any( b=>b.CategoryId == categoryId)
|| c.Products.Any( p=>p.CategoryId == categoryId)
select new
{
c.CompanyId,
c.CompanyName,
c.Country.Flag,
c.Profile,
c.IsUsingSMSNotifications,
c.IsVerified,
c.MembershipType,
c.RegistrationDate, c.ShortProfile,
}).Skip(skip).Take(take).ToList();
SSMS使用的查询检查CategoryId = 1并使用AND条件,但您的LINQ查询使用OR条件