Using " Is NULL/not NULL" in LINQ To SQL - sql

i would like to translate this request in LINQ to SQL:
SELECT * from Agir where NouvelIncident='1' AND facturable is null
My try:
public static List<Agir> GetINDEFAgir()
{
DataClassesActilogDataContext db = ContextSingleton.GetDataContext();
List<Agir> list;
var v = from i in db.Agir
where i.facturable is null && i.NouvelIncident == true
select i;
list = v.ToList();
return list;
}
Looks like "is null" is not allowed in LINQ to SQL... i have a mistake.
Thanks in advance for your help

Use ==, 'is' is to check types
public static List<Agir> GetINDEFAgir()
{
DataClassesActilogDataContext db = ContextSingleton.GetDataContext();
List<Agir> list;
var v = from i in db.Agir
where i.facturable == null && i.NouvelIncident == true
select i;
list = v.ToList();
return list;
}

Doesn't this work?
var v = from i in db.Agir
where i.facturable == null && i.NouvelIncident == true
select i;
Linq-to-SQL should translate that to the proper SQL.

Related

Easiest way to check record is exist or not in Linq to Entity Query

in store procedure we can check record is exist or not using following query for fast performance
if EXISTS ( Select 1 from Table_Name where id=#id )
But what about Linq query.
right now i have to store whole data in object like this
UserDetail _U=db.UserDetails.where(x=>x.id==1).FirstOrDefault();
Any Solution?
Use Linq's Any ie bool exist = db.UserDetails.Any(x => x.id == 1);
if(db.UserDetails.Any(x => x.id == 1)) {
var userDetail = db.UserDetails.FirstOrDefault(x => x.id == 1);
}
bool exist = db.UserDetails.Where(x=>x.id==1).Any();
if(exist){
//your-code
}else{
//your-code
}
Just check
if(_U == null)
This way you will get what you want in single query and you not need to execute addition query like
db.UserDetails.Any(x => x.id == 1)
I think, it does not require to fire two query. It can be accomplish by single query.
UserDetails objUserDetails =db.UserDetails.FirstOrDefault(x => x.id == 1);
if(objUserDetails==null)
{
// Do something
}
else
{
// do something with objUserDetails
}
var qry = db.User_Detail.Where(x => x.User_Id == 1).FirstOrDefault();
if(qry !=null)
{
// Do something
}
else
{
return false;
}
Try This...

Database.Count Null Value

int userId;
int follow = 0;
if (Session["userId"] != null)
{
userId = int.Parse(Session["userId"].ToString());
follow = Model.Follow.Count(x => x.EdenUserId == userId);
}
Error Code: Value cannot be null.
There exists some users who don't follow anybody so Count should be 0 but it returns null.
If user is following any user, table is populated without problem.
Can anyone please explain how can I count when there is a possibility that the lambda expression might return null?
Try:
int userId;
int follow = 0;
if (Session["userId"] != null)
{
userId = int.Parse(Session["userId"].ToString());
follow = Model.Follow.Count(x => x.EdenUserId == userId) == null? 0: Model.Follow.Count(x => x.EdenUserId == userId);
}

WPF application Linq to sql getting data

I'm making a WPF application with a datagrid that displays some sql data.
Now i'm making a search field but that doesn't seem to work:
Contactpersoon is an nvarchar
bedrijf is an nvarchar
but
LeverancierPK is an INT
How can I combinate that in my search?
If i convert LeverancierPK to string, then I can use Contains but that gives me an error
//Inisiatie
PRCEntities vPRCEntities = new PRCEntities();
var vFound = from a in vPRCEntities.tblLeveranciers
where ((((a.LeverancierPK).ToString()).Contains(vWoord)) ||
(a.Contactpersoon.Contains(vWoord)) ||
(a.Bedrijf.Contains(vWoord)))
orderby a.LeverancierPK
select a;
myDataGrid_Leveranciers.ItemsSource = vFound;
Thanks
If you don't care about pulling all records back from the DB (which in your answer you pulled everything back), then you can just do a .ToList() before the where clause.
var vFound = vPRCEntities.tblLeveranciers.ToList()
.Where(a => a.LeverancierPK.ToString().Contains(vWoord)) ||
a.Contactpersoon.Contains(vWoord) ||
a.Bedrijf.Contains(vWoord))
.OrderBy(a.LeverancierPK);
This code can do what I was looking for but I think it could be alot shorter.
PRCEntities vPRCEntities = new PRCEntities();
var vFound = from a in vPRCEntities.tblLeveranciers
orderby a.LeverancierPK
select a;
myDataGrid_Leveranciers.ItemsSource = null;
myDataGrid_Leveranciers.Items.Clear();
foreach (var item in vFound)
{
if (item.Bedrijf.Contains(vWoord))
{
myDataGrid_Leveranciers.Items.Add(item);
}
else
{
if (item.LeverancierPK.ToString().Contains(vWoord))
{
myDataGrid_Leveranciers.Items.Add(item);
}
else
{
if (item.Contactpersoon != null)
{
if (item.Contactpersoon.Contains(vWoord))
{
myDataGrid_Leveranciers.Items.Add(item);
}
}
}
}
}

How to create a Dynamic Query when there's a condition that won't use all fields in the where section with LinQ

I am using a Data Entity from the db, and a Domain Service.
I am using .net's generated code for the simple queries, like this
public IQueryable<employee> GetEmployeesByLocale(int localeID)
{
return ObjectContext.employees.Where(e => e.Locale_ID == localeID);
}
Now, I need to change the .Where section accordingly, so:
if (localeID > 0)
{
['Where' should be like .Where(e => e.Locale_ID == localeID)];
}
if (projectID > 0)
{
[IF localeID == 0, 'Where' should be like .Where(e => e.Project_ID == projectID)
Else if localeID > 0, Where should use both, sort of .Where(e => e.Locale_ID == localeID && e.Project_ID == projectID)];
}
and so on with other variables.
There are many possible combinations , which is why I was trying to use the overload for .Where(string, parameter[])
string q = string.Empty;
if (localeID > 0)
{
q = "Locale_ID = " + localeID.ToString();
}
if (projectID > 0)
{
q = q == string.Empty ? "Project_ID = " + projectID.ToString() : q + " and " + "Project_ID = " + projectID.ToString();
}
... (for other variables and fields)
...
System.Data.Objects.ObjectParameter[] param = new System.Data.Objects.ObjectParameter[1];
param[0] = new System.Data.Objects.ObjectParameter("param", 1);
return ObjectContext.employees.Where(q, param);
However, this only gives an error, because then all the fieldnames are supposedly out-of-scope/non-existing. Even if use employees.[field_name] in the string, they "don't exist"
Does anyone know of a way to use conditionals inside the .Where part of the query? Or how to create some var or object containing my query so I can just parse it?
You can use
IQueryable<Employee> emp = ObjectContext.employees;
if (localeID > 0)
emp=emp.Where(e => e.Locale_ID == localeID).AsQueryable();
if (projectID > 0)
emp=emp.Where(e => e.Project_ID == projectID).AsQueryable();
This will concatenate the where clauses

What is the linq equivalent to the SQL IN operator

With linq I have to check if a value of a row is present in an array.
The equivalent of the sql query:
WHERE ID IN (2,3,4,5)
How can I do it?
.Contains
var resultset = from x in collection where new[] {2,3,4,5}.Contains(x) select x
Of course, with your simple problem, you could have something like:
var resultset = from x in collection where x >= 2 && x <= 5 select x
Perform the equivalent of an SQL IN with IEnumerable.Contains().
var idlist = new int[] { 2, 3, 4, 5 };
var result = from x in source
where idlist.Contains(x.Id)
select x;
db.SomeTable.Where(x => new[] {2,3,4,5}.Contains(x));
or
from x in db.SomeTable
where new[] {2,3,4,5}.Contains(x)
Intersect and Except are a little more concise and will probably be a bit faster too.
IN
collection.Intersect(new[] {2,3,4,5});
NOT IN
collection.Except(new[] {2,3,4,5});
or
Method syntax for IN
collection.Where(x => new[] {2,3,4,5}.Contains(x));
and NOT IN
collection.Where(x => !(new[] {2,3,4,5}.Contains(x)));
An IEnumerable<T>.Contains(T) statement should do what you're looking for.
A very basic example using .Contains()
List<int> list = new List<int>();
for (int k = 1; k < 10; k++)
{
list.Add(k);
}
int[] conditionList = new int[]{2,3,4};
var a = (from test in list
where conditionList.Contains(test)
select test);
The above situations work when the Contains function is used against primitives, but what if you are dealing with objects (e.g. myListOrArrayOfObjs.Contains(efObj))?
I found a solution! Convert your efObj into a string, thats separated by _ for each field (you can almost think of it as a CSV representation of your obj)
An example of such may look like this:
var reqAssetsDataStringRep = new List<string>();
foreach (var ra in onDemandQueueJobRequest.RequestedAssets)
{
reqAssetsDataStringRep.Add(ra.RequestedAssetId + "_" + ra.ImageId);
}
var requestedAssets = await (from reqAsset in DbContext.RequestedAssets
join image in DbContext.Images on reqAsset.ImageId equals image.Id
where reqAssetsDataStringRep.Contains(reqAsset.Id + "_" + image.Id)
select reqAsset
).ToListAsync();
You can write help-method:
public bool Contains(int x, params int[] set) {
return set.Contains(x);
}
and use short code:
var resultset = from x in collection
where Contains(x, 2, 3, 4, 5)
select x;
Following is a generic extension method that can be used to search a value within a list of values:
public static bool In<T>(this T searchValue, params T[] valuesToSearch)
{
if (valuesToSearch == null)
return false;
for (int i = 0; i < valuesToSearch.Length; i++)
if (searchValue.Equals(valuesToSearch[i]))
return true;
return false;
}
This can be used as:
int i = 5;
i.In(45, 44, 5, 234); // Returns true
string s = "test";
s.In("aa", "b", "c"); // Returns false
This is handy in conditional statements.