how can write this in CS what is should replace **** with ??
MSSQL Query:
SELECT *FROM Advertisement INNER JOIN
SubCategory ON Advertisement.SubCategoryID = SubCategory.SubCategoryID INNER JOIN
CategoryHaveSubCategory ON SubCategory.SubCategoryID = CategoryHaveSubCategory.SubCategoryID INNER JOIN
Category ON CategoryHaveSubCategory.CategoryID = Category.CategoryID WHERE (CategoryHaveSubCategory.CategoryID = 1)
C# Query:
query = (from a in db.Advertisements
orderby a.Date descending
where **** && a.Deleted == false
select a).Skip(skip).Take(PAGE_SIZE);
You didn't include an important part of your Advertisement entity - the navigation properties. From the relation shown I assume you have something like this
class Advertisement
{
// ...
public SubCategory SubCategory { get; set; }
}
Then the condition you are asking for should be something like this
where a.SubCategory.Categories.Any(c => c.CategoryID == 1) && a.Deleted == false
query = (from a in db.Advertisements
orderby a.Date descending
where a.SubCategory.Categories.Any(c => c.CategoryID == 1)
&& a.Deleted == false
select a).Skip(skip).Take(PAGE_SIZE);
Related
Basically I want to create an inner or join. In SQL:
SELECT COUNT(*) FROM Discounts
JOIN DiscountArticles ON Discounts.ID = DiscountArticles.Discount
JOIN Articles ON (DiscountArticles.Article = Articles.ID OR DiscountArticles.ArticleGroup = Articles.ArticleGroup)
This answer says, it's not possible using entity framework, however we can use an cross join, which works fine on SQL:
SELECT COUNT(*) AS GroupCount FROM Discounts
JOIN DiscountArticles ON Discounts.ID = DiscountArticles.Discount
CROSS JOIN Articles
WHERE (Articles.ID = DiscountArticles.Article OR Articles.ArticleGroup = DiscountArticles.ArticleGroup)
So I tried this:
var query = from discounts in _dbContext.Discounts
join discountArticles in _dbContext.DiscountArticles on discounts.Id equals discountArticles.Discount
from article in _dbContext.Articles
where article.Id == discountArticles.Article || article.ArticleGroup.Value == discountArticles.ArticleGroup.Value
select new
{
ArticleId = article.Id,
DiscountId = discounts.Id
};
However, this resolves into this this SQL query:
SELECT [a].[ID] AS [ArticleId], [d].[ID] AS [DiscountId]
FROM [Discounts] AS [d]
INNER JOIN [DiscountArticles] AS [d0] ON [d].[ID] = [d0].[Discount]
CROSS JOIN [Articles] AS [a]
WHERE ([a].[ID] = [d0].[Article]) OR (([a].[ArticleGroup] = [d0].[ArticleGroup]) OR (([a].[ArticleGroup] IS NULL) AND ([d0].[ArticleGroup] IS NULL)))
As you can see, there is an addtional check OR (([a].[ArticleGroup] IS NULL) AND ([d0].[ArticleGroup] IS NULL)), which is causing to return 6 time more results.
ArticleGroup is Nullable Guid? on both entities, so I guess it has something to do with it.
If I additional check it for null, I get the correct results:
where article.Id == discountArticles.Article ||
article.ArticleGroup.HasValue && article.ArticleGroup == discountArticles.ArticleGroup
However, I also get an bigger where clause in SQL:
WHERE ([a].[ID] = [d0].[Article]) OR (([a].[ArticleGroup] IS NOT NULL) AND ([a].[ArticleGroup] = [d0].[ArticleGroup]))
Is it somehow possible to generate a Query, which is more like my second SQL example? Something like this:
WHERE (Articles.ID = DiscountArticles.Article OR Articles.ArticleGroup = DiscountArticles.ArticleGroup)
Try this query, it will create appropriate join. I do not think that you need CROSS JOIN here.
var query =
from discounts in _dbContext.Discounts
join discountArticles in _dbContext.DiscountArticles on discounts.Id equals discountArticles.Discount
from article in _dbContext.Articles
.Where(article => article.Id == discountArticles.Article || article.ArticleGroup.Value == discountArticles.ArticleGroup.Value)
select new
{
ArticleId = article.Id,
DiscountId = discounts.Id
};
According to null comparison, check this option Using relational null semantics. Bad here that it will affect all queries:
services.AddDbContext<MyDbContext>(options =>
{
options.UseSqlServer(sourceConnection, sqlOptions =>
{
sqlOptions.UseRelationalNulls();
});
});
I have a query in sql, as shown in the code below:
select *
from Registration r
inner join RegistrationService rs on rs.RegistrationID = r.RegistrationID
inner join Service s on s.ServiceID = rs.ServiceID
where cast(RegistrationDate as DATE) between #startDate and #endDate
and s.ByDoctor = 'false'
and rs.ServiceID not in (select ServiceID from TreatmentService ts where ts.TreatmentID = r.RegistrationID)
Now I have to convert this into linq syntax because I'm using EF as my data access. I'm getting a problem when converting the last line:
rs.ServiceID not in (select ServiceID from TreatmentService ts where ts.TreatmentID = r.RegistrationID)
and my linq syntax:
var query = context.Registrations.Where(r =>
DbFunctions.TruncateTime(r.RegistrationDate) == DbFunctions.TruncateTime(DateTime.Today)
&&
r.RegistrationServices.Any(rs => rs.Service.ByDoctor == false)
&&
!(context.TreatmentServices.Select(ts => ts.ServiceID).Where(ts => ts.TreatmentID == r.RegistrationID)).Contains(rs.ServiceID) <-- here is the problem
);
How to solve this?
Why not use the linq query-like syntax?
from r
in context.Registration
join rs in context.RegistrationService on rs.RegistrationID = r.RegistrationID
join s in context.Service on s.ServiceID = rs.ServiceID
...
Taken from: LINQ query examples
from r
in context.Registration
join rs in context.RegistrationService on rs.RegistrationID equals r.RegistrationID
join s in context.Service on s.ServiceID equals rs.ServiceID
where s.Where(ts=>ts.TreatmentID == r.RegistrationID).All(ts => ts.ServiceID != rs.ServiceID )
I don't know it its possible to have a nested or 2 or more on c.blah equals b.blah in one join statement in LINQ bacause i have to join a table without affecting the number of data
because if I add it to where theres a decrease of number of data and it acts as filter
What I tried as of the moment is adding && clause but it's not working
var Pos = (from a in db.Position
join b in db.Position_Location
on a.ID equals b.PositionId
join c in db.Customer
on a.CustomerID equals c.ID
join d in db.Customer_Location
on b.LocationId equals d.ID
join f in db.Worker
on userIdNew equals f.userId
join e in db.Worker_Customer_Apply_Shift <----Planning to add new validation here
on a.ID equals e.Client_Customer_PositionID into trial
from newtrial in trial.DefaultIfEmpty()
where
b.LogicalDelete == false
&& a.LogicalDelete == false
&& c.LogicalDelete == false
&& d.LogicalDelete == false
select new
{
a.ID,
Client_CustomerID = c.ID,
LogicalDelete =(newtrial == null ? true : newtrial.LogicalDelete),
}).Distinct().ToList();
Thanks in Advance :)
You could use an anonymous type with the fields you want use in your join condition:
on new { a.One, a.Two } equals new { b.One, b.Two }
If the columns in both tables don't have the same names, you need to provide names for the properties of the anonymous type:
on new { Col1 = a.One, Col2 = a.Two } equals new { Col1 = b.Three, Col2 = b.Four }
I want to be able to pull the last invoice containing a product in a category
Category->Product->Invoice
(from p as Product in cat
where p.InvoiceList.Where(function(o) o.InvoiceDate >= MAX_ONE)
select p.InvoiceList.Where(function(o) o.InvoiceDate >= MAX_ONE)
).FirstOrDefault()
I just can't seem to wrap my head about how to get this done.
EDIT: a sample SQL statement that would accomplish my goal. If only I could translate it...
SELECT TOP 1 i.InvoiceID, i.InvoiceDate, i.TotalAmount
FROM Category as c INNER JOIN
Product as p ON p.categoryID = c.categoryID INNER JOIN
InvoiceProducts as ip ON ip.productID = p.productID INNER JOIN
Invoice as i ON ip.InvoiceID = i.InvoiceID
WHERE c.categoryID = 3
ORDER BY InvoiceDate DESC
cat.SelectMany(p => p.InvoiceList).OrderBy(o => o.InvoiceDate).LastOrDefault();
var lastInvoice = (from i in context.Invoices
.where i.Product.CategoryId == categoryId
.select i)
.OrderByDescending(i=>i.IbvoiceDate)
.FirstOrDefault();
I have a search method below using linq, my search citeria is based on one table so far but I have a particular citeria which requires another table :
Method:
public void search(string s)
{
var db = new CommerceEntities();
var products =
from p in db.Products
where (p.ModelName != null && p.ModelName.Contains(s))
|| SqlFunctions.StringConvert((double) p.ProductID).Contains(s)
|| (p.ModelNumber != null && p.ModelNumber.Contains(s))
|| (p.Description != null && p.Description.Contains(s))
|| SqlFunctions.StringConvert((double) p.CategoryID).Contains(s)
|| //stuck - See comment below
/* so far all in 'products' table, but I have one more citeria here that needs 'categories' table.
Ok, the query in SQL statement will be like this:
select ProductID, ModelName, ProductImage, Unitcost, products.Categoryid
from categories
join products
on (categories.CategoryID = products.categoryID)
where categories.categoryname = 'necklace' (replace necklace with my parameter 's')
order by products.ModelName
I am not sure how to 'integrate' it with my existing linq query. Please kindly advice. Thanks.
*/
select new
{
// Display the items
p.ProductID,
p.ModelName,
p.ProductImage,
p.UnitCost,
p.CategoryID,
};
ListView_Products.DataSourceID = null;
ListView_Products.DataSource = products;
}
var products = from p in db.Products
join c in categories on c.CategoryID equals p.categoryID
where (/* all you conditions in either tables */)
select new
{
p.ProductID,
p.ModelName,
p.ProductImage,
p.UnitCost,
p.CategoryID
/* plus what ever you want from categories */
};