i have the sql below that i would like to convert to C# using linq. Can someone tell me how this best can be done with linq?
select A.field1, A.Field2, A.Field4, A.Field5, A.Field4 ,A.Field6
from MPhoneParts A
where A.Field3= 'Batteri' AND NOT EXIST(
select * from MPhoneParts B where
B.Field3='cover'
A.Field2= B.Field2 AND
A.Field4= B.Field4 AND
B.Field6='Production354')
Cheers
Mike
There may be a better approach (quite possibly using a join...), but:
var query = from a in db.MPhoneParts
where a.Field3 == "Batteri" &&
!db.MPhoneParts.Any(b => b.Field3 == "cover" &&
a.Field2 == b.Field2 &&
a.Field4 == b.Field4 &&
b.Field6 == "Production354")
select a;
I assume your question is mistyped and you meant to check for the NOT IN clause.
here is the solution on how to write the NOT IN... in linq, hope this helps:
The NOT IN clause in LINQ to SQL
var qry =
from a in db.PhoneParts
where a.Field3 == "Batteri"
&& !db.PhoneParts.Any(b =>
b.Field3 == "cover"
&& b.Field6 == "Production354"
&& b.Field2 == a.Field2
&& b.Field4 == a.Field4)
select new { a.Field1, a.Field2, a.Field4, a.Field5, a.Field6 };
But thoughts:
Field1 thru Field6 are horrible names
you can use the existing SQL via db.ExecuteQuery
Related
I am new to LINQ queries and want to use FirstOrDefault in my existing LINQ query.
List<vUserAll> employee = (from o in db.vUsersAll
where (o.sAMAccountName == modifiedAccountName || o.CN == modifiedAccountName) && o.Domain == "dExample"
select o).ToList();
What's the correct way to do this?
This can be simplified further as:
var filtered = db.vUsersAll.FirstOrDefault(u => u. Field == filter);
If the above mentioned is the case, then you can use a labmda as in the following:
var firstOrDefaultResult = db.vUsersAll.Where(o=>
(o.sAMAccountName == modifiedAccountName || o.CN == modifiedAccountName)
&& o.Domain == "dExample").FirstOrDefault()
If you want to use the same above expression then,
vUserAll employee = (from o in db.vUsersAll
where (o.sAMAccountName == modifiedAccountName || o.CN == modifiedAccountName) && o.Domain == "dExample"
select o).FirstOrDefaul();
It's a lot easier if you only use LINQ extensions. For example,
var filtered = all users.Where(u => u. Field == filter).FirstOrDefault();
This question already has answers here:
Linq: adding conditions to the where clause conditionally
(9 answers)
Closed 3 years ago.
I am creating a wcf application which is connecting to DB to get some data for customer using Entity Framework. The concept is to search a customer based on the search parameters. User can provide all or few or at least one of the search parameters. But I am quite new in Entity Framework and getting confused on how to do this. I can do this in traditional SQL coding by considering If - Else condition in c# side.
This is my code which is getting the all of the paramters:
var customers = from o in natCustomer.CustomerLists
select o;
customers = customers.Where(c => c.Name == sName && c.Age == iAge
&& c.Gender == sGender && c.Height == dHeight && c.Weight == dWeight
&& c.Nationality == sNationality
&& c.EyeColor == sEyeColor && c.SpecialMark == sSpecialMark);
Please help me by suggesting how do I get the result with few or one parameter only.
Thanks
Entity Framework queries are "deferred" queries. They don't actually run until you start asking for results. This means you can build up a query in pieces and it will (mostly) work exactly like one bigger query.
In your case, you can do something like:
var customers = from o in natCustomer.CustomerLists
select o;
if (!string.isNullOrEmpty(sName))
customers = customers.Where(c => c.Name == sName);
if (!string.isNullOrEmpty(sNationality))
customers = customers.Where(c => c.sNationality == sNationality);
if (!string.isNullOrEmpty(SpecialMark ))
customers = customers.Where(c => c.SpecialMark == SpecialMark);
etc. At the end, when you execute the customers query (for example, call ToList or use a foreach loop) EF will consolidate all of those smaller Where clauses into a single SQL query to run against your data.
Assuming you only want to find customers who match on all non-null parameters, an alternative approach is to include the null checks within the where query, and only compare the parameter to the customer data if the parameter is not null.
customers = customers.Where(c => (string.isNullOrEmpty(sName) || c.Name == sName)
&& (iAge == null || c.Age == iAge)
&& (string.isNullOrEmpty(sGender) || c.Gender == sGender));
You need some way to determine if the given inputs are set or not. For a simplification I assume you receive your parameters as nullables. So you could add an additional condition, if the parameter is provided:
customers = sName == null ? customers : customers.Where(c => c.Name == sName);
customers = iAge == null ? customers : customers.Where(c => c.Age == iAge);
customers = sGender == null ? customers : customers.Where(c => c.Gender == sGender);
...
I have a ternary operator as below for a LINQ query as shown
var sub = (SubordinationType == 1) ? (true&false) : false;
var query = from vw in dbContext.vw
where (vw.office == FieldOffice && vw.SubAgreement == sub)
select vw;
Here SubAgreement is a bit field in database I need to select both true and false(0,1) or false(0) based on the ternery how do i achieve this?
Any quick suggestions please.
I think I get your question. Your logic is:
If Subordination is 1, SubAgreement doesn't matter (true or false)
If Subordination is not 1, SubAgreement should be false
hence add another condition:
//..
where (vw.office == FieldOffice && (Subordination == 1 || !vw.SubAgreement))
Try something like:
var query = from vw in dbContext.vw
where vw.office == FieldOffice
select vw;
if (SubordinationType != 1)
{
query = query.Where(vw => vw.SubAgreement == false);
}
In LINQ it's very easy to add new where clauses that are in && with the other clauses (note that it's only easy to add if you want them to be in &&, the || case is much more complex! :-) )
You can make a condition that is true when SubordinationType is 1 or when SubAgreement is false:
var query = from vw in dbContext.vw
where (vw.office == FieldOffice && (SubordinationType == 1 || vw.SubAgreement == false))
select vw;
Using the StackExchange.Profiling.MiniProfiler class to profile an ASP.NET MVC application with Linq-To-Sql as ORM.
I'm trying to reduce one action to one SQL, so that I don't have any duplicates anymore.
So I changed my linq-to-sql code accordingly, but it didn't have any positive effect on the speed.
Then I checked the time that is needed for the SQL.
This shows the MiniProfiler:
When I fire up the exact same SQL in Management Studio it is super fast:
Here is the code:
from t in type
let tDoc = (from d in context.documents
where d.Key == t.No
&& d.RType == (int)RType.Art
&& d.AType == (int)AType.Doc
select d).FirstOrDefault(d => d.UseForThumb)
select new Time
{
Id = t.Id,
//... more simple mappings here
// then a complex one:
DocsCount = context.documents.Count(d =>
(d.Key == t.Id.ToString()
&& d.RType == (int)RType.Type
&& d.AType == (int)AType.Doc)
||
(d.Key == t.No
&& d.RType == (int)RType.Art
&& d.AType == (int)AType.Doc)),
// and another one
ThumbId = (tDoc != null && tDoc.FRKey.HasValue) ? tDoc.FRKey.Value : 0
};
What can be the reason for the huge difference? - Edit: There is no difference, I just misenterpreted SSMS :(
Anyway, my problem persits. What could I change to make it faster?
I read sometime that the mapping from Linq-To-Sql has a performance problem. Is there a way to workaround this?
I did some trial and error and changed the Linq-To-Sql code to this:
from t in types
let docs = context.documents.Where(d => (d.RKey == t.Id.ToString()
&& d.RType == (int)RType.Type
&& d.AType == (int)AType.Doc)
||
(d.RKey == t.No
&& d.RType == (int)RType.Art
&& d.AType == (int)AType.Doc))
let tDoc = docs.FirstOrDefault(d => d.RType == (int)RType.Art && d.UseForThumb)
let docsCount = docs.Count()
select new Time
{
Id = t.Id,
//... more simple mappings here
DocsCount = docsCount,
ThumbId = (tDoc != null && tDoc.FRKey.HasValue) ? tDoc.FRKey.Value : 0,
}
This made the query much, much faster.
I'm writing a linq query in query syntax and I'm wondering how to add another where clause.
Basically, I have the following:
var test = from t in MyDC.TheTable
where t.UserID == TheUserID
where t.DateDone.Date == TheDate.Date
select new MyModel {.....};
TheTable has a column called LinkedID and this column is also in another table called ColorStatus (a number between 1 and 10). I'm looking to write the where clause "where the LinkedID in the ColorStatus table is less than 7".
Thanks.
Just a suggestion on improving the statement you have. You can actually merge the two where conditions into a single one. && means "AND"
Where t.UserID == TheUserID && t.DateDone.Date = TheDate.Date
Your information "another table called ColorStatus" doesn't make sense here.
var test = from t in MyDC.TheTable
where t.UserID == TheUserID
&& t.DateDone.Date == TheDate.Date
&& t.LinkedID < 7
select new MyModel {.....};
Probably I didn't get your idea, here is an example of join may help you.
var test = from t in MyDC.TheTable
join x in MyDC.ColorStatus
on t.LinkedID == x.LinkedID
where t.UserID == TheUserID
&& t.DateDone.Date == TheDate.Date
&& x.AnotherField == 1
select new MyModel {.....};