ASP.NET Entity Framework, if empty string - contains - c#

I have query like this:
var listAds = (from a in _db.Ads
where
a.Animal.Contains(animal) &&
a.AnimalBreed.Contains(breed) &&
GeoCodeCalc.CalcDistance(a.X, a.Y, 51.919438, 19.145136) <= distance
select a).ToList();
If my string (breed or animal) is empty, then not find any record..
How to make it work even if the string is empty?
Thanks for reply, best regards.

small addition to Kirill's answer:
Checks null (if would) values too.
Update:
Sorry "animal" doesnt exists.
it should be:
var listAds = (from a in _db.Ads
where
(a.Animal.Contains(animal)|| string.IsNullOrEmpty(a.Animal)) && (a.AnimalBreed.Contains(breed)||string.IsNullOrEmpty(a.AnimalBreed)) &&
GeoCodeCalc.CalcDistance(a.X, a.Y, 51.919438, 19.145136) <= distance
select a).ToList();

Try this:
var listAds = (from a in _db.Ads
where
(a.Animal.Contains(animal)||animal=="") &&
(a.AnimalBreed.Contains(breed)||animal=="") &&
GeoCodeCalc.CalcDistance(a.X, a.Y, 51.919438, 19.145136) <= distance
select a).ToList();

If I understood correctly
If my string (breed or animal) is empty, then not find any record..
then you could do like in the following snippet
var listAds = (from a in _db.Ads
where
(animal != string.Empty && breed != string.Empty) &&
a.Animal.Contains(animal) &&
a.AnimalBreed.Contains(breed) &&
GeoCodeCalc.CalcDistance(a.X, a.Y, 51.919438, 19.145136) <= distance)
select a).ToList();

Related

FirstOrDefault LINQ query with a condition

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();

simple SQL query to LinQ , i have tried but not solved yet

I have the following SQL Server query and I need to have it in LINQ, Simple query but I tried several time but I can not get it working.
Here is the SQL query
select *
from td_Accountline
where
BonusPlanID = 1
and Amount > 0
and Ord_Sub_ID like '%SMPORD%'
and MONTH(Created) = 11
and YEAR(Created) = 2013
and Ord_Sub_ID not in (
select Ord_Sub_ID
from td_Accountline
where
BonusPlanID =3 and
Ord_Sub_ID like '%SMPORD%'
)
I have tried with this query but still i am confused
var account=from acc in currentDB.td_Accountline
where acc.BonusPlan.BonusPlanID == 1 && acc.Amount > 0 && acc.Ord_Sub_ID.Contains("SMPORD") && acc.Created.ToDateTime().Month == 11 && acc.Created.ToDateTime().Year == 2013
let accNot = from accN in currentDatabase.td_Accountline
where accN.BonusPlan.BonusPlanID == 3 && accN.Ord_Sub_ID.Contains("SMPORD")
select accN.Ord_Sub_ID
where !accNot.Contains("SMPORD")
select acc;
I want one query please not separate query to reduce database calling.
I think you're almost there. Instead of:
where !accNot.Contains("SMPORD")
It should be:
where !accNot.Contains(acc.Ord_Sub_ID)
Your final Linq query would be:
var account = from acc in currentDB.td_Accountline
where
acc.BonusPlan.BonusPlanID == 1
&& acc.Amount > 0
&& acc.Ord_Sub_ID.Contains("SMPORD")
&& acc.Created.Month == 11
&& acc.Created.Year == 2013
let accNot = from accN in currentDatabase.td_Accountline
where
accN.BonusPlan.BonusPlanID == 3
&& accN.Ord_Sub_ID.Contains("SMPORD")
select accN.Ord_Sub_ID
where !accNot.Contains(acc.Ord_Sub_ID)
select acc;
Regular Expressions won't work in Linq for Entity Framework but you can convert to collection in an in-memory list for you to use Regex.
Something like this:
(from x in td_Accountline where Created.Month = 11 && Created.Year = 2013 select a).ToList().Where(v => Regex.IsMatch(v.Ord_Sub_ID,#"(SMPORD)"))
That way, the match will happen in memory
Try This :
var Ord_Sub_IDs = from n in td_Accountline where n.BonusPlanID == 3 && n.Ord_Sub_ID.Contains("SMPORD") select n.Ord_Sub_ID ;
var result=from n in td_Accountline where n.BonusPlanId == 1 && n.Amount > 0 && n.Ord_Sub_ID.Contains("SMPORD") && n.Created.ToDateTime().Month == 11 && n.Created.ToDateTime().Year == 2013 && Ord_Sub_IDs.Contains(td.Ord_Sub_ID) select n;

Using Linq in domain service in Silverlight

I kind of feel guilty asking this question because asked a smiliar one before but I did not get a clear answer. I am building a silverlight program and I need to create a Linq query in the domain service (using wcf ria). I need to calculate the sum here is my code
int lola = (from c in context.GetTRANSACTIONSQuery()
where ((c.CHART_ACC == transStudID) && (c.sch_year == 13))
select c).Sum();
MessageBox.Show(lola.ToString());
Between the parenthesis at Sum() I get an error that says
Error 1 Instance argument: cannot convert from 'System.ServiceModel.DomainServices.Client.EntityQuery' to 'System.Collections.Generic.IEnumerable'
What am I missing?? I know it is syntax problem because I am new to Linq. Please Thank you!
What are you adding up for Sum()? Can you try:
int lola = (from c in context.GetTRANSACTIONSQuery()
where ((c.CHART_ACC == transStudID) && (c.sch_year == 13))
select c.PROPERTYTHATYOUWANTTOADDUP).Sum();
Or perhaps you wanted to count how many items match your query?
int lola = (from c in context.GetTRANSACTIONSQuery()
where ((c.CHART_ACC == transStudID) && (c.sch_year == 13))
select c).Count();
EDIT:
So since you want to add up the AMOUNT property:
decimal lola = (from c in context.GetTRANSACTIONSQuery()
where ((c.CHART_ACC == transStudID) && (c.sch_year == 13))
select (decimal)c.AMOUNT).Sum();
You can also make sure that c.AMOUNT is never null so you don't run into an error in the future:
decimal lola = (from c in context.GetTRANSACTIONSQuery()
where ((c.CHART_ACC == transStudID) && (c.sch_year == 13) && (c.AMOUNT != null))
select (decimal)c.AMOUNT).Sum();

"LINQ to Entities does not recognize the method" when Convert to Int 32

Before post this question i try search based on my problem i couldn't find one (may be am not search that well :(, i was trying to convert my string to integer in the linq query i got this exception.
**
LINQ to Entities does not recognize the method 'Int32
ToInt32(System.String)' method, and this method cannot be translated
into a store expression
**
Posting full query might be time wasting for you guys so i just dropped the main line where i get stuck
int intBookingNumber = Convert.ToInt32(Booktime);
var query =
(from PROJECTS in db.PROJECTS
join WOes in db.WOes on PROJECTS.PRJ_ID equals WOes.PRJ_ID
join SEVTs in db.SEVTs on WOes.SEQNUM equals SEVTs.SEQNUM
join RSRCEs in db.RSRCEs on SEVTs.RESID equals RSRCEs.RESID
join PERS in db.PERS on RSRCEs.RECID equals PERS.RECID into PERS_join
from PERS in PERS_join.DefaultIfEmpty()
join RESTYPEs in db.RESTYPEs on new { RTYPE = SEVTs.RTYPE } equals new { RTYPE = RESTYPEs.CODE }
join RESCATs in db.RESCATs on new { RCAT = SEVTs.RCAT } equals new { RCAT = RESCATs.CODE }
join SEVT_EX in db.SEVT_EX on SEVTs.SESID equals SEVT_EX.SESID into SEVT_EX_join
from SEVT_EX in SEVT_EX_join.DefaultIfEmpty()
where
(new string[] { "1", "2" }).Contains((PROJECTS.STAT.TrimEnd()).TrimStart()) &&
(WOes.STAT.TrimEnd()).TrimStart() == "6" &&
((SEVTs.RESTYPE == 5 ||
SEVTs.RESTYPE == 0) &&
(RESTYPEs.USER2.Substring(2 - 1, 1) == "F" &&
RESTYPEs.USER2.Substring(6 - 1, 1) == "S") &&
SEVTs.TYPE == 0) ||
(SEVTs.RESTYPE == 4 &&
SEVTs.TYPE == 0) &&
RESCATs.GROUPID==0 &&
RESTYPEs.GROUPID==0 &&
(int?)(WOes.INVOICE.TrimStart()).Length > 0 &&
WOes.INVOICE.TrimStart() != "PENDING" &&
WOes.USERFLAG1 != 1 &&
//(SEVTs.T_START.TrimStart()) == (Booktime)
//Convert.ToInt32(SEVTs.T_START.TrimStart()) >= Convert.ToInt32(Booktime)
Convert.ToInt32(SEVTs.T_START) >= intBookingNumber
orderby
PROJECTS.PRJ_ID,
WOes.WONUM
select new
{
PROJECTS.PRJ_ID,
PROJECTS.USER3,
PROJECTS.USER9,
WOes.WONUM,
WOes.JOBDESC,
SEVTs.SESID,
SEVTs.RESTYPE,
SEVTs.TYPE,
SEVTs.T_START,
SEVTs.T_END,
SEVTs.MEALEND,
SEVTs.MELSTART3,
SEVTs.MELSTART2,
SEVTs.MELEND2,
Column1 = SEVTs.MELSTART2,
SEVTs.MELEND3,
SEVTs.USER2,
SEVTs.SUBACTID,
SEVTs.OT_EXEMPT,
USER5 = SEVT_EX.USER5,
SEVTs.GMT_OFFSET,
SEVTs.MEALSTART,
SEVTs.STANDARD,
RESCATs.USER1,
SEVTs.RESID
});
SEVTs.T_START.TrimStart() and bookingStart both data types are string. Obviously they are getting numbers here . how can i use the logic operator here.
Any help much appreciated.
Find the work around guys, this help me to solve my problem
**String.Compare(SEVTs.T_START.TrimStart(), Booktime) >= 0**
Whats the actual DataType of the T_START? if Int and nullable this might be your solution. notice the .Value and .HasValue
Where ...
SEVTs.T_START.HasValue && (SEVTs.T_START.Value >= intBookingNumber)
...
Found the work around guys, this help me to solve my problem
**String.Compare(SEVTs.T_START.TrimStart(), Booktime) >= 0**

How to convert this sql to Linq C#

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

Categories

Resources