"invalidcastexception specified cast is not valid linq" exeception in LINQ query - linq

var Player = from PSI in regConfig.Player_SeasonalInfos
from PPI in regConfig.Player_PermanentInfos
where PSI.PaymentId == PlayerPayment.PaymentId
&& PPI.PlayerId == PSI.PlayerId
select new {
PlayerIds = string.Join(",", PSI.PlayerId),
PlayerSeasonalId = PSI.PlayerSeasonalId,
CityId = PPI.CityId
};
foreach (var item in Player)
{
Player_SeasonalInfo PlayerSeasonalInfos =
(from PSI in regConfig.Player_SeasonalInfos
where PSI.PlayerSeasonalId ==item.PlayerSeasonalId
select PSI).FirstOrDefault();
PlayerSeasonalInfos.StatusId = item.CityId == 1 ? 1 : 2;
regConfig.SubmitChanges();
}
i have write this code but i am getting excepiton"invalidcastexception specified cast is not valid linq" on line"
from PSI in regConfig.Player_SeasonalInfos
where PSI.PlayerSeasonalId ==item.PlayerSeasonalId
select PSI"
please suggest.

Related

How to get list of results in Linq

I'm taking a list of counts, averaging and returning all results according to the condition. Looks like my command is too erroneous. I don't know how to do it yet.
I have tables:
var qr = (from Product c in _context.Products
join o in _context.RatingProducts on c.ID equals o.IDProduct
where c.Status == true
orderby c.NumProduct
group o by c.ID into g
select new {
ProductId = g.Key,
CountID = g.Count(),
//SumID = g.Sum(s => s.StarRating).ToString(),
AveragedID = g.Count() > 0 ? g.Average(x => x.StarRating) : 0
}).ToList();
var getqr = _context.Products.Where(a => a.Status).ToList();
int count = 0;
double averaged = 0;
foreach (var item in getqr)
{
int key = item.ID;
var id = qr.Where(x => x.ProductId == key).FirstOrDefault();
if(id != null)
{
count = id.CountID;
averaged = Math.Round(id.AveragedID,1);
}
var productquery = item;
}
var query = from c in qr
join p in getqr on c.ProductId equals p.ID
select new ProductQuery
{
ID = p.ID,
IDProduct = p.IDProduct,
CategoryID = p.CategoryID,
NumProduct = p.NumProduct,
Name = p.Name,
Status = p.Status,
Price = p.Price,
PriceOld = p.PriceOld,
ContentsSmall = p.ContentsSmall,
Contents = p.Contents,
Images = p.Images,
CountID = count,
//SumID = c.SumID,
AveragedID = averaged,
};
return query.ToList();
However when I debug, it shows only one result with row ID = 1. I want to display list: count, average results of table 1. Tks.
As far as I understand you should make LEFT JOIN here, so need to add DefaultIfEmpty in the initial query, and slightly change average counting logic.
Something like this, should work:
var qr = (from Product c in _context.Products
join o in _context.RatingProducts on c.ID equals o.IDProduct into productRatings
from pr in productRatings.DefaultIfEmpty()
where c.Status == true
orderby c.NumProduct
group o by c.ID into g
select new {
ProductId = g.Key,
CountID = g.Count(),
AveragedID = g.Average(x => x == null ? 0 : x.StarRating)
}).ToList();

EF Core performance issue when using dynamic query using Expressions in .Net

Requirement : Select list of records from table for members whose ID and First name matches with records.
The number of members in the request may vary as per the request:
I have written following code to generate dynamic query using expressions.
private Expression<Func<TmpOncMemberAuth, bool>> CreateQueryExpression(List<MemberRequest> memberRequests)
{
var type = typeof(TmpOncMemberAuth);
// member =>
var memberParam = Expression.Parameter(type, "member");
var requests = memberRequests;
Expression selectLeft = null;
Expression filterExpression = null;
foreach (var member in requests)
{
var comparison = BuildSubQuery(member, memberParam, type);
if (selectLeft == null)
{
selectLeft = comparison;
filterExpression = selectLeft;
continue;
}
filterExpression =
Expression.Or(filterExpression, comparison);
}
return Expression.Lambda<Func<TmpOncMemberAuth, bool>>
(filterExpression, memberParam);
}
private Expression BuildSubQuery(MemberRequest member, ParameterExpression memberParam, Type type)
{
// LHS
// member.MemberID
Expression leftMemberID = Expression.Property(memberParam, type.GetProperty("MemberId"));
Expression leftMemberFirstName = Expression.Property(memberParam, type.GetProperty("MemberFirstName"));
// RHS
Expression requestMemberID = Expression.Constant(member.MemberID);
Expression requestFirstName = Expression.Constant(member.FirstName);
// member.MemberID == requestMemberID
Expression compareID =
Expression.Equal(leftMemberID, requestMemberID);
Expression compareFName =
Expression.Equal(leftMemberFirstName, requestFirstName);
// condition for a member
Expression comparison = Expression.AndAlso(compareID, compareFName);
return comparison;
}
// query call in the main
var whereQuery = CreateQueryExpression(memberData);
var memberAuthData = await FindAllAsyncFromTemp(whereQuery);
This generate a SQL query in the below format, which take a lot time
SELECT [#].[CaseID] AS [CaseId], [#].[MemberID] AS [MemberId], [#].[MemberFirstName], [#].[MemberLastName], [#].[MemberDOB]
FROM [#ONCMemberAuth] AS [#]
WHERE ((CASE
WHEN (([#].[MemberID] = '12345') AND ([#].[MemberFirstName] = 'James') ) THEN CAST(1 AS bit)
ELSE CAST(0 AS bit)
END | CASE
WHEN (([#].[MemberID] = '6789') AND ([#].[MemberFirstName] = 'WILLERS') ) THEN CAST(1 AS bit)
ELSE CAST(0 AS bit)
END)
) = CAST(1 AS bit)
I need to create SQL query like below which executes faster than the above one
SELECT [#].[CaseID] AS [CaseId], [#].[MemberID] AS [MemberId], [#].[MemberFirstName], [#].[MemberLastName], [#].[MemberDOB]
FROM [#ONCMemberAuth] AS [#]
WHERE ((([#].[MemberID] = '1234') AND ([#].[MemberFirstName] = 'James')) OR (([#].[MemberID] = '56789') AND ([#].[MemberFirstName] = 'WILLERS') ) )

How to optimize slow LINQ query?

I tried delete a statement that use contain() and use skip() take()
but it's still take a long time on execution
public JsonNetResult GetList(C.Lib.ListParam param, string type, DateTime? WorkDate, string MNo, string ANo, string AName, string Specifi, string PNo, string SName, string PType, string OrNo)
{
var idObj = (mis.Models.Security.CIdentity)Csla.ApplicationContext.User.Identity;
var c = new mis.Models.CEntities();
var targetList = (from obj in c.WorkOrders
join obj2 in c.Partners on obj.PartnerId equals obj2.PartnerId
join obj3 in c.Assets on obj.AssetsId equals obj3.AssetsId
join obj4 in c.WorkOrderItems on obj.WorkOrderId equals obj4.WorkOrderId
join obj5 in c.WorkItems on obj4.WorkId equals obj5.WorkId
join obj6 in c.Products on obj3.AssetsId equals obj6.AssetsId
where true && obj.TenantId == idObj.TenantId && obj2.Customer == true && obj.WorkOrderStatus <= 1
select new
{
WorkProgressId = obj.WorkOrderId,
OrderNo = obj.InOrderItem.OrderItem.Order.OrderNo,
ProductType = obj5.ProductType,
WorkOrderId = obj.WorkOrderId,
MakeQty = obj.MakeQty,//delete some column
PrepaidDate = obj.PrepaidDate,
CompleteDate = (from subobj in c.WorkOrderItems
where subobj.WorkOrderId == obj.WorkOrderId && subobj.CompleteDate != null
orderby subobj.CompleteDate descending, subobj.WorkItem.WorkNo descending
select subobj.CompleteDate).FirstOrDefault(),
WorkNoName = (from subobj in c.WorkOrderItems
where subobj.WorkOrderId == obj.WorkOrderId && subobj.CompleteDate != null
orderby subobj.WorkItem.WorkNo descending
select new { WorkNoName = subobj.WorkItem.WorkNo + " " + subobj.WorkItem.WorkName }).FirstOrDefault().WorkNoName,
});
targetList = targetList.GroupBy(x => x.MakeNo).Select(x => new
{
WorkProgressId = x.FirstOrDefault().WorkOrderId,
OrderNo = x.FirstOrDefault().OrderNo,
ProductType = x.FirstOrDefault().ProductType,
WorkOrderId = x.FirstOrDefault().WorkOrderId,
WorkOrderDate = x.FirstOrDefault().WorkOrderDate,
OrderQty = x.FirstOrDefault().OrderQty,
MakeQty = x.FirstOrDefault().MakeQty,
PrepaidDate = x.FirstOrDefault().PrepaidDate,//delete some column
CompleteDate = x.FirstOrDefault().CompleteDate,
WorkNoName = x.FirstOrDefault().WorkNoName
}).OrderByDescending(x => x.WorkOrderDate).ThenByDescending(x => x.WorkNoName);
param.SetCount(targetList);
targetList.OrderByDescending(x => x.WorkOrderDate).ThenByDescending(x=> x.WorkNoName);
var tk= targetList.Skip((param.Page - 1) * param.Rows).Take(param.Rows);
return JsonNetHelper.ReturnData(param,tk);
}
I'm wondering what is the best way to optimize it? Or would the query profiler do that for me?

Left outer join with multiple on conditions in LINQ

basically i want to check DestinationCustomerList with SA_CUSTOMER_ALLOC if any record found based on customerId and fieldId then return priority else priority = 1 , so i am using left outer join with entity but it's not working properly(returning only matching record and if SA_CUSTOMER_ALLOC doesn't have any record throwing "Object referenece error" how to handle this.
var Query = (from p in DestinationCustomerList
join p2 in Context.SA_CUSTOMER_ALLOC on new { f1 = p.CustomerId, f2 = p.FieldId } equals new { f1 = p2.CUSTOMER_ID, f2 = p2.FIELD_ID }
into temp
from x in temp.DefaultIfEmpty()
where x.TAG_ID == TagId && x.REGION_ID == RegionId
select new { p.CustomerId,p.FieldId, Priority = x == null ? 1 : x.PRIORITY }).ToList();
Instead of Priority = x == null ? 1 : x.PRIORITY
try Priority = p2 == null ? 1 : p2.PRIORITY
var Query = (from p in DestinationCustomerList
join p2 in Context.SA_CUSTOMER_ALLOC
on new
{ f1 = p.CustomerId, f2 = p.FieldId }
equals new
{ f1 = p2.CUSTOMER_ID, f2 = p2.FIELD_ID }
into temp
from x in temp.DefaultIfEmpty()
let priority = p2 == null ? 1 : p2.PRIORITY
where x.TAG_ID == TagId && x.REGION_ID == RegionId
select new { p.CustomerId,p.FieldId, Priority = priority }).ToList();

Combining Sub Queries Into 1 Query Linq

Is there a way I can rewrite the following query to make it just one query?
try
{
var fileIds = (from f in context.SignalTo
where f.SignalFileID == 2
select new { f.GFileID }).ToList();
foreach (var id in fileIds)
{
var pp = (from p in context.ProjectFiles
where p.FileID == id.GFileID && p.ProjectID == ProjectID
select p);
if (pp != null)
{
ProjectFiles projectFile =(ProjectFiles) pp;
projectFile.MStatus = Status;
projectFile.DateLastUpdated = DateTime.Now;
context.SaveChanges();
}
}
}
You can combine the two query parts of your code into one.
You would then need to loop over the result set, making your updates. You would then call context.SaveChanges to submit all changes in one batch.
I can't tell if your existing code actually runs or compiles, but you need something like this:
Get the list of file ids you're interested in:
var fileIds = from f in context.SignalTo
where f.SignalFileID == 2
select f.GFileID;
fileIds is at this point an IQueryable where I assume T is an Int. No query has been excuted yet.
Now you can do
var pps = from p in context.ProjectFiles
where fileIds.Contains(p.FileID) && p.ProjectID == ProjectID
select p;
Still no query executed.
Then iterate over the result set
foreach( var pp in pps ) // query executed now
{
pp.MStatus = Status;
pp.DateLastUpdated = DateTime.Now;
}
context.SaveChanges(); // batch of updates executed now

Resources