Multiple OR in SQL statement with Linq - c#

I have a question with Linq to Sql query in C#.
I have this query:
from A in context.General
join B in context.Applications on A.ID equals B.ID
from G in context.Notes
//where (G.CODE == A.NoteID || G.CODE == A.NoteID2 || G.CODE == A.NoteID3)
join X in context.Att on B.AttID equals X.AttID
select new
{
A.SomeStuff,
B.SomeStuff
G.NOTE_TEXT
});
My question is, which NOTE_TEXT the query will return, for example if in some case one record has three codes that match with the G.CODE field it will return three NOTE_TEXT or only the first one? Or in another case what happens if one record has only one match with the G.CODE field, and the others two has an empty value, only return that match or nothing?
Thank you so much, and please let me know if I'm not clear in my question.

Related

Only include in where condition if date is not low date(01/01/0001)

I have a query that has a where condition to check and find addresses that were added after a certain date. The date field is not required so I want Date field in where condition to be only considered if it is not 1/1/0001.
dtmDate is the parameter that is being passed
Query
from b in _context.customer
join d in _context.Address on b.id equals d.Id
join e in _context.units on d.Id equals e.Id
where (req.dtmDate.Year != 1 && d.DateAdded >= req.dtmDate)
select new modelAddress
{
address= d.address
}
But this is not working. It is not returning any rows
I'd leverage the fact that LINQ queries are not executed when you write them, so you can add clauses conditionally after you've created a base query:
var query = from b in _context.customer
join d in _context.Address on b.id equals d.Id
join e in _context.units on d.Id equals e.Id;
if(req.dtmDate.Year != 1)
query = query.Where(d.DateAdded >= req.dtmDate);
var result = query.Select(
new modelAddress
{
address= d.address
}
);
I prefer this because I've previously run into issues, particularly with EF LINQ queries when the Where clause contains something that evaluates to true locally with in the code, rather than as something the DB will evaluate. It seems to work out better when "wildcarding" DB queries, to use a pattern of "if x is true then add-another-where-clause" rather than saying "where(local-value-of-x-equals-local-constant OR some-db-data-value-equals-y)"
If I understand you correctly, you have a DateTime object called req.dtmDate that may be set to a default value, and you want to return all items where the item's DateAdded field is greater than req.dtmDate, unless req.dtmDate is 1/1/0001, in which case all records should be returned.
If that's the case, I think you could just modify your existing code to:
where (req.dtmDate.Year == 1 || d.DateAdded >= req.dtmDate)

Operators "AND" "OR" SQL [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Hello I'm trying to transform this code from SQL to C# using Linq
The SQL code is like this:
SELECT N.Name,N.Unit,N.Typee,ID,NOTE
FROM Table_A N join Table_B A on (N.ID = A.ID)
join NotasQL G on ((N.Not1 = G.CODE) or (N.Not2 = G.CODE) )
join Attributes X on (A.AppID= X.AppID)
This Code is running fine in SQL with the expected result, but when I'm trying to replicate this on C# I don't know how to do the OR part, this is what I have so far:
var Select = (from A in context.Table_A
from B in context.Table_B
from E in context.NotasQLs
from D in context.Attributes
where (String.Compare(A.ID, B.ID, true) == 0 &&
String.Compare(B.AppID, D.AppID, true) == 0
&&
(String.Compare(A.Not1, E.CODE, true) == 0 ||
String.Compare(A.Not2, E.CODE, true) == 0))
I'm having an application runtime expired because the query is not selecting nothing, if I remove the or condition runs but I need the OR.
For translating SQL to LINQ query comprehension:
Translate FROM subselects as separately declared variables.
Translate each clause in LINQ clause order, translating monadic and aggregate operators (DISTINCT, TOP, MIN, MAX etc) into functions applied to the whole LINQ query.
Use table aliases as range variables. Use column aliases as anonymous type field names.
Use anonymous types (new { ... }) for multiple columns.
JOIN conditions that aren't all equality tests with AND must be handled using where clauses outside the join, or with cross product (from ... from ...) and then where
JOIN conditions that are multiple ANDed equality tests between the two tables should be translated into anonymous objects
LEFT JOIN is simulated by using into joinvariable and doing another from from the joinvariable followed by .DefaultIfEmpty().
Replace COALESCE with the conditional operator (?:)and a null test.
Translate IN to .Contains() and NOT IN to !...Contains().
Translate x BETWEEN low AND high to low <= x && x <= high.
SELECT * must be replaced with select range_variable or for joins, an anonymous object containing all the range variables.
SELECT fields must be replaced with select new { ... } creating an anonymous object with all the desired fields or expressions.
Proper FULL OUTER JOIN must be handled with an extension method.
So for your query,
var ans = from N in Table_A
join A in Table_B on N.ID equals A.ID
from G in NotasQL
where G.CODE == N.Not1 || G.CODE == N.Not2
join X in Attributes on A.AppID equals X.AppID
select new {
N.Name,
N.Unit,
N.Typee,
N.ID, // ??? not sure table for this column
G.NOTE // ??? not sure table for this column
};

Linq query involving 4 joined tables, to a many to many table

I need to return true when any record either has an Indemnity type of bond, or has the bond waived. I think because of the way inner joins are happening this is not working.
var HasBondorWaived = (from a in context.Allocations
join p in context.Permits on a.PermitGUID equals p.GUID
join i in context.Indemnities on a.IndemnityGUID equals i.GUID
join t in context.IndemnityTypes on a.IndemnityAreaTypeGUID equals t.GUID
where (p.GUID.Equals(PermitGuid)
&& (t.Description.Equals("Performance Bonds") || t.Description.Equals("Payment Bonds")))
|| p.BondRequirementWaived where p.GUID.Equals(PermitGuid)
select a).Any();
return HasBondorWaived;
I'm getting closer. My validation is now working correctly in the case of "Performance Bond" or "Payment Bond", but is not working in the case of BondRequirementWaved. This is a bool in the EF, and a bit in SQL server. In the case of BondRequirementWaved, it is returning false.
using (var context = new KEPTEntities())
{
var HasBondorWaived = (from a in context.Allocations
join p in context.Permits on a.PermitGUID equals p.GUID
join i in context.Indemnities on a.IndemnityGUID equals i.GUID
join t in context.IndemnityTypes on i.IndemnityTypeGUID equals t.GUID
where (p.GUID.Equals(PermitGuid)
&& (t.Description.Equals("Performance Bonds")
|| t.Description.Equals("Payment Bonds")
|| p.BondRequirementWaived))
select a).Any();
return HasBondorWaived;
The second where clause won't work as you expect. You need to remove it.
You probably want this:
where (p.GUID.Equals(PermitGuid)
&& (t.Description.Equals("Performance Bonds") || t.Description.Equals("Payment Bonds")
|| p.BondRequirementWaived))
Assuming you have navigation properties set up, this is much cleaner:
var HasBondorWaived=context.Allocations
.Where(a=>a.Permits.GUID.Equals(PermitGuid))
.Any(a=>a.Permits.BondRequirementWaived ||
a.Indemnities.Any(i=>i.IdemnityType.Description=="Performance Bonds" || i.IdemnityType.Description=="Payment Bonds"));
Kind of hard to see what you actually asking for, but I think that is what you want based on your question and without a clear entity model.

LINQ: Join conditionally to two different tables depending on each item

Is there any way to set if in a linq statement?
return(from x in db.products where x.id == id
if(x.type == 1){
join y in db.category1 on x.idItem equals y.id
}else if(x.type == 2){
join z in db.category2 on x.idItem equals z.id
}
select New {....}).ToList();
I know this code is wrong but my question is:
What's the best way to implement this?
Note, that the following does not solve the problem that the OP is having because the join predicate depends on each item. The following helps if the condition is known for the entire query at once:
You split the query:
var part1 = from x in db.products where x.id == id select x;
var part2 =
b ? (from x in part1 join db.category1 select { x, joinedItem }) :
(from x in part1 join db.category2 select { x, joinedItem });
Quickly written up. You need to make the anonymous types on both queries compatible. That's the only important thing.
You could do a LEFT JOIN and one of the conditions of the LEFT JOIN could be the condition you have in the IF clause. So, you always do all the LEFT JOINs but they will only return results when the condition you have in the IF cluase is true.
Another way, with much better performance, is to create a Stored Procedure and call it from EF.

linq left join with where clause show all from left table regardless

Im struggling with some linq
I want everything from the CustomerDiscountGroups table, then join a column from another table. If the where condition shows ther are no CustomerDiscounts i still want it to show all the colums from CustomerDiscountGroups table, and state 0 for Discount_PC ( a decimal)
heres my attempt
from c in CustomerDiscountGroups
join d in CustomerDiscounts on c.ID equals d.Discount_ID into cd
from cdi in (from f in cd
where f.AccountNo == "test"
select f).DefaultIfEmpty()
select new
{
c.ID,
c.DisplayName,
c.Image,
c.Added,
c.Added_by,
c.Edited,
c.Edited_by,
//cdi.Discount_PC
}
DefaultIfEmpty will make cdi null, even though it is of the type CustomerDiscounts. You have to handle that situation in your select clause:
select new
{
c.ID,
c.DisplayName,
c.Image,
c.Added,
c.Added_by,
c.Edited,
c.Edited_by,
Discount_PC = cdi == null ? 0 : cdi.Discount_PC
}
It is a bit awkward to have to write out a ternary operator for it and in fact, in C#6 there will probably be a new short hand operator for this.

Categories

Resources