Getting the wrong count? - c#

I am getting the wrong count error and I can't figure out why.
In my database serverId = 1/2/3 has only one started value and 3 notstarted value for each server.
painfo = (from paes in server.AppPM_Paes
where (paes.PaStatus == "Started" || paes.PaStatus == "NotStarted" ) && paes.ServerId != null
select new PaDetails { ServerID = paes.ServerId, PaStatus = paes.PaStatus }).ToList();
foreach (PaDetails a in painfo)
{
if (a.PaStatus.Contains("Started") && a.ServerID.Equals(1))
stCount1++;
if (a.PaStatus.Contains("Started") && a.ServerID.Equals(2))
stCount2++;
if (a.PaStatus.Contains("Started") && a.ServerID.Equals(3))
stCount3++;
if (a.PaStatus.Contains("NotStarted") && a.ServerID.Equals(1))
notStCount1++;
if (a.PaStatus.Contains("NotStarted") && a.ServerID.Equals(2))
notStCount2++;
if (a.PaStatus.Contains("NotStarted") && a.ServerID.Equals(3))
notStCount3++;
}
But in my above code (stCount#->started count), stCount# has the value 4 instead of 1.
What's wrong in my code?
Can you please help me?

You're doing a .Contains("Started"). This will include any string that has the word "Started" in it, including "NotStarted"
You can change it to a.PaStatus == "Started" or a.PaStatus.Equals("Started")

Related

Select based on where condition using linq

I want to use select query using linq to list.
in fallowing code userDtls is an list & Common.UserRightVal is an enum variable
userDtls = _userService.GetById(id);
var permission = from udtls in userDtls[0].userRightList
where udtls.object_name == "Person" &&
(udtls.user_right == (int)Common.UserRightVal.update
|| udtls.user_right == (int)Common.UserRightVal.add_update_delete_read
|| udtls.user_right == (int) Common.UserRightVal.allRight)select udtls;
Here I want to check permission details for user. My question is if 'where' condition is getting false then also permission variable is showing default records as shown by userDtls list.
Thanks to every one for response. I got answer, here it is.
var permission=(dynamic) null;
permission = (from udtls in userDtls[0].userRightList
where udtls.object_name.Contains(objectType) &&
(udtls.user_right == (int)Common.UserRightVal.readAll
|| udtls.user_right == (int)Common.UserRightVal.read_readAll
|| udtls.user_right == (int)Common.UserRightVal.add_update_delete_read
|| udtls.user_right == (int)Common.UserRightVal.allRight)
select udtls).FirstOrDefault();

How to improve Linq-To-Sql code

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.

"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**

Optimizing A LINQ To Objects Query

I'm trying to optimize the below LINQ query to improve it's speed performance. The number of objects it's searching against could be in the tens of thousands.
var lQuery = from o in oEvents
where (o.oSalesEvent != null && o.oSalesEvent.OccurDate < oCalcMgr.OccurDate && (
(oCalcMgr.InclTransTypes == Definitions.TransactionTypes.SalesAll) ?
(o.oSalesEvent.EventStateID == ApprovedID || o.oSalesEvent.EventStateID == PendingID) :
o.oSalesEvent.EventStateID == ApprovedID)) &&
((oCalcMgr.InclTransTypes == Definitions.TransactionTypes.SalesAll) ?
(o.oSalesMan.oEmployment.EventStateID == ApprovedID || o.oSalesMan.oEmployment.EventStateID == PendingID) :
o.oSalesMan.oEmployment.EventStateID == ApprovedID)
select new { SaleAmount = o.SaleAmount.GetValueOrDefault(), CompanyID = o.oSalesEvent.CompanyID };
The query basically says, give me the sales amounts and company ids from all sale events that occurred prior to a certain date. The sale event's status and the salesman's employment status should either always be "approved" or they can be also "pending" if specified.
As you can see there's a date comparison and a couple of integer comparisons. Which integer comparison used is based on whether or not a property matches a certain Enum value.
I have some ideas of my own on ways to go about the optimization, but I want to hear others thoughts, who might have more insight into how LINQ would translate this query behind the scenes.
Thanks
It seems to me that your biggest challenge is that you're doing multiple criteria checks in your Linq statement that will take alot of time.
What about creating a new property in oEvents - Say "IsEligable" and set it's value within the Set statements of your other variables (much faster than constant re-querying of each variable in the Linq).
Then, by the time you get to this part of your code, you could update your Linq to be something along the lines of:
var lQuery = from o in oEvents
where (o.oSalesEvent != null && o.oSalesEvent.OccurDate < oCalcMgr.OccurDate && o.IsEligable == True)
select new { SaleAmount = o.SaleAmount.GetValueOrDefault(), CompanyID = o.oSalesEvent.CompanyID };
... I'm guessing that would speed up the execution, but just a thought...
This is as much to improve readability as to possibly speed it up, but give this a try:
var lQueryTemp = from o in oEvents
where (o.oSalesEvent != null && o.oSalesEvent.OccurDate < oCalcMgr.OccurDate)
if (oCalcMgr.InclTransTypes == Definitions.TransactionTypes.SalesAll)
{
lQueryTemp = from o in lQueryTemp
where (o.oSalesEvent.EventStateID == ApprovedID || o.oSalesEvent.EventStateID == PendingID) &&
(o.oSalesMan.oEmployment.EventStateID == ApprovedID || o.oSalesMan.oEmployment.EventStateID == PendingID);
}
else
{
lQueryTemp = from o in lQueryTemp
where (o.oSalesEvent.EventStateID == ApprovedID && o.oSalesMan.oEmployment.EventStateID == ApprovedID);
}
var lQuery = from o in lQueryTemp
select new { SaleAmount = o.SaleAmount.GetValueOrDefault(), CompanyID = o.oSalesEvent.CompanyID };
This might speed it up by pulling out both checks of oCalcMgr.InclTransTypes, which is effectively a constant for purposes of this query.

linq - include where parameters

I have a strange question about Linq.
I have this query:
var results = (from p in hotsheetDB.Properties
where p.PCode == pCode
&& p.PropertyStatusID == propertyStatuses
orderby p.PropertyID descending
select new
{
PropertyId = p.PropertyID,
PCode = p.PCode,
PropertyTypeName = p.cfgPropertyType.Name,
FullAddress = p.Address1 + " " + p.Address2,
ZipCode = p.ZipCode.Code,
CityName = p.cfgCity.Name,
LivingSquareFeet = p.LivingSquareFeet,
LotSquareFeet = p.LotSquareFeet,
NumBedrooms = p.NumBedrooms,
NumBathrooms = p.NumBathrooms,
PropertyStatusName = p.cfgPropertyStatuse.Name
});
You notice pCode and propertyStatuses parameters. They are input values from the users. He wants to search by pCode or/and by propertyStatuses.
So, when the user fills in only pCode he wants to return all the records with that pCode having ANY propertyStatuses...well, because propertyStatuses IS in the query but it's null, the query will not return anything (because there is no record with empty(null) propertyStatuses...
Therefore, the question: is there any way to include these where params only whey they have values? (without making separate N queries with all the combination? (I have multiple inputs)
Thanks in advance..
You could change your where clause to make the parts which include null always return true.
For example:
where (pCode == null || p.PCode == pCode)
&& (propertyStatuses == null || p.PropertyStatusID == propertyStatuses)
I'm only guessing here but try:
where p.PCode == pCode &&
(p.PropertyStatusID == null || p.PropertyStatusID == propertyStatuses)

Categories

Resources