Error within Where statement in LINQ - linq

For some reason in my where it says that "firstname" does not exist in the Opportunity Entity. But it is set for the SystemUser Entity. Any idea why it is getting confused? Thanks!
var linqQuery = (from r in gServiceContext.CreateQuery("opportunity")
join c in gServiceContext.CreateQuery("account") on ((EntityReference)r["accountid"]).Id equals c["accountid"]
join u in gServiceContext.CreateQuery("systemuser") on ((EntityReference)r["ownerid"]).Id equals u["systemuserid"]
where r["new_leadstatus"].Equals("100000004") && u["lastname"].Equals(rsmLastName) && u["firstname"].Equals(rsmFirstName)
select new
{
AccountId = !r.Contains("accountid") ? string.Empty : r["accountid"],
Account = !r.Contains("name") ? string.Empty : r["name"]
});

Make sure you put each where clause in its own line per Microsoft guidelines.
The where clause applies a filter to the results, often using a
Boolean expression. The filter specifies which elements to exclude
from the source sequence. Each where clause can only contain
conditions against a single entity type. A composite condition
involving multiple entities is not valid. Instead, each entity should
be filtered in separate where clauses.
var linqQuery = from r in gServiceContext.CreateQuery("opportunity")
join c in gServiceContext.CreateQuery("account") on ((EntityReference)r["accountid"]).Id equals c["accountid"]
join u in gServiceContext.CreateQuery("systemuser") on ((EntityReference)r["ownerid"]).Id equals u["systemuserid"]
where r["new_leadstatus"].Equals("100000004")
where u["lastname"].Equals(rsmLastName) && u["firstname"].Equals(rsmFirstName)
select new
{
AccountId = !r.Contains("accountid") ? string.Empty : r["accountid"],
Account = !r.Contains("name") ? string.Empty : r["name"]
};

You define your reference to the Opportunity entity as 'r' but are trying to read firstname from 'u'
from r in gServiceContext.CreateQuery("opportunity")
u["firstname"]
Change the end of your where to
r["firstname"].Equals(rsmFirstName)

Related

Unable to create a constant value of type 'System.DBNull'. Only primitive types or enumeration types are supported in this context

I try to apply left outer join on the basis of two ids one in the primary key of one table while the foreign key of another table also nullable
var yarnPOFilter_Grid = (from yrq in _context.Yarn_Requisition_Details
//join ypo in
_context.Yarn_PurchaseOrder_Details on yrq.YarnRequsitionDetailID
equals
ypo.YarnRequsitionDetailID into t
join ypo in
_context.Yarn_PurchaseOrder_Details on yrq.YarnRequsitionDetailID
equals
DBNull.Value.Equals(ypo.YarnRequsitionDetailID) ? 0 :
ypo.YarnRequsitionDetailID into t
from rt in t.DefaultIfEmpty() //
DefaultIfEmpty preserves left-hand elements that have no matches on the
right side
select new
{
YarnRequsitionDetailID =
(rt.YarnRequsitionDetailID == null ? long.MinValue :
rt.YarnRequsitionDetailID),
yrq.YarnID,
yrq.Yarn.YarnName,
yrq.YarnFellowID,
yrq.Yarn_FellowCodes.YarnFellowCode,
yrq.QuantityRequired,
rt.QuantityOrdered,
QuantityBalance_Custom =
yrq.QuantityRequired - rt.QuantityOrdered
}).ToList();
return yarnPOFilter_Grid;
I get this error message when I deal with null in joining condition
Unable to create a constant value of type 'System.DBNull'. Only primitive types or enumeration types are supported in this context.
Execute ToList() First before Select as there is no sql equivalent to the conditions you added in the YarnRequsitionDetailID = (rt.YarnRequsitionDetailID == null ? long.MinValue : rt.YarnRequsitionDetailID)
so it will be
from rt in t.DefaultIfEmpty()).ToList().Select(c => new
{
YarnRequsitionDetailID =
(c.rt.YarnRequsitionDetailID == null ? long.MinValue :
c.rt.YarnRequsitionDetailID),
c.yrq.YarnID,
c.yrq.Yarn.YarnName,
c.yrq.YarnFellowID,
c.yrq.Yarn_FellowCodes.YarnFellowCode,
c.yrq.QuantityRequired,
c.rt.QuantityOrdered,
QuantityBalance_Custom =
c.yrq.QuantityRequired - c.rt.QuantityOrdered
}).ToList();
i hope this solved your previous problem

How to solve this Error in Linq : Operator '!=' cannot be applied to operands of type 'int' and 'System.Linq.IQueryable<int>'

var ll = from a in db.EmployeeMasters
where a.EmployeeID != (from d in db.EmployeeMasters
join c in db.PerformanceDetails on d.EmployeeID equals c.EmployeeID
join z in db.ProjectMasters on c.ProjectID equals z.ProjectID
into ss
from z in ss.DefaultIfEmpty()
where z.ProjectName == name || z.ProjectName == name1
select d.EmployeeID)
select a.EmployeeName;
It returns an error messages like below
Operator '!=' cannot be applied to operands of type 'int' and 'System.Linq.IQueryable'
I want to add this Linq query in http post method to view output in postman
Anyone Please help me to solve this
Actual question is select employees who are not part of 2 projects like (CRM, Automation)
Part of both project employees are in another project but some of the employees not in any projects
My Entity Framework Data Model is shown here:
name and name1 are given parameters for project names
You're making this much harder than necessary. In the first place, you should use these navigation properties EF kindly creates for you, instead of using verbose and error-prone join statements. Doing that, it's much easier to write a greatly simplified predicate:
var ll = from a in db.EmployeeMasters
where !a.PerformanceDetails
.Any(pd => pd.ProjectMaster.ProjectName == name
|| pd.ProjectMaster.ProjectName == name1)
select a.EmployeeName;
This is a different query --it translates into EXISTS-- but the result is the same and the query plan may even be better. Also, it's much easier to add more predicates to it later, if necessary.
Your question isn't really clear, but the error is pretty clear, you cannot compare type int and System.Linq.IQueryable<int>.
I assume your want something like this :
var ll = from a in db.EmployeeMasters
where !(from d in db.EmployeeMasters
join c in db.PerformanceDetails on d.EmployeeID equals c.EmployeeID
join z in db.ProjectMasters on c.ProjectID equals z.ProjectID
into ss
from z in ss.DefaultIfEmpty()
where z.ProjectName == name || z.ProjectName == name1
select d.EmployeeID).Contains(a.EmployeeID)
select a.EmployeeName;
Here we're looking for EmployeeIDs that do not appear in your query result.
int[] EmployeeIDs = (from em in db.EmployeeMasters
join pd in db.PerformanceDetails on em.EmployeeID equals pd.EmployeeID into pdRes
from pdResult in pdRes.DefaultIfEmpty()
join pm in db.ProjectMasters on pdResult.ProjectID equals pm.ProjectID into pmRes
from pmResult in pmRes.DefaultIfEmpty()
where (pmResult.ProjectName == "Automation" || pmResult.ProjectName == "CRM Customer")
select em.EmployeeID
).Distinct().ToArray();
var empResult = (from em in db.EmployeeMasters
where !EmployeeIDs.Contains(em.EmployeeID)
select new
{
EmployeeName = em.EmployeeName
}).ToList();

LINQ Error when using multiple JOIN in same statement on CRM 2011 Plug-in

Hi I am trying to join multiple entities in CRM 2011 but I get and error saying: {"'xrmsm_sessionEnrollments' entity doesn't contain attribute with Name = 'xrmsm_termsid'."}. That is correct but I am joining the entity that have that attribute.
My Linq Query:
var query2 = from e in svsContext.xrmsm_sessionEnrollmentsSet
join s in svsContext.xrmsm_sessionsSet on e.xrmsm_SessionLookup.Id equals s.xrmsm_sessionsId
join ic in svsContext.xrmsm_institutionCoursesSet on s.xrmsm_institutionCourseLookup.Id equals ic.xrmsm_institutionCoursesId
join ts in svsContext.xrmsm_term_sessionsSet on e.xrmsm_termSessionLookup.Id equals ts.xrmsm_term_sessionsId
join t in svsContext.xrmsm_termsSet on ts.xrmsm_TermLookup.Id equals t.xrmsm_termsId
where (e.xrmsm_StudentLookup.Equals(studentlookup)
&& e.xrmsm_YearLookup.Equals(entity.GetAttributeValue("xrmsm_studentlookup"))
&& ic.xrmsm_institutionCoursesId == institutionCourseGuid
&& t.xrmsm_termsId == termGuid)
select new { sessionName = s.xrmsm_sessionsName, StudentName = e.xrmsm_studentsName, StudentId = e.xrmsm_StudentLookup.Name };
My original SQL query that works on SQL Server:
SELECT en.xrmsm_currentsessionenrollmentsname
,en.xrmsm_isreadonlyname
,en.xrmsm_sessionenrollmentsaverage
,en.xrmsm_sessionenrollmentsgrade
,en.xrmsm_sessionenrollmentsid
,en.xrmsm_sessionenrollments_id
,en.xrmsm_sessionlookup as sessionid
,en.xrmsm_sessionlookupname
,en.xrmsm_sessionsname
,en.xrmsm_studentlookup AS studentid
,en.xrmsm_studentlookupname
,en.xrmsm_studentsname
,en.xrmsm_termsessionlookup
,en.xrmsm_termsessionlookupname
,en.xrmsm_withdrawal
,en.xrmsm_yearaverage
,en.xrmsm_yeargrade
,en.xrmsm_yearlookup
,en.xrmsm_yearlookupname
FROM CoseyTest_MSCRM.dbo.Filteredxrmsm_sessionEnrollments as en INNER JOIN
CoseyTest_MSCRM.dbo.Filteredxrmsm_sessions crmsessions ON
(en.xrmsm_sessionlookup = crmsessions.xrmsm_sessionsid AND en.xrmsm_yearlookup = crmsessions.xrmsm_yearlookup)
INNER JOIN Filteredxrmsm_institutionCourses institutionCourses
on crmsessions.xrmsm_institutioncourselookup = institutionCourses.xrmsm_institutioncoursesid
Inner Join Filteredxrmsm_term_sessions as termsession
on en.xrmsm_termsessionlookup = termsession.xrmsm_term_sessionsid
Inner Join Filteredxrmsm_terms as terms
on termsession.xrmsm_termlookup = terms.xrmsm_termsid
where en.xrmsm_yearlookup = '4BA07BED-3F51-E211-8359-00155D004403'
and en.xrmsm_studentlookup = 'C844AF65-5B51-E211-8359-00155D004403'
and terms.xrmsm_termsid = 'D1D107B7-4551-E211-8359-00155D004403'
and institutionCourses.xrmsm_institutioncoursesid = '2121914E-4551-E211-8359-00155D004403'
Linq provider for CRM has some limitations. You can fount it here. Check if your query violates limitations.
Try having a look at the actual query that it is generating and run that in SQL, it may help understand what is going on.
It could be that something your doing in LINQ is not available in CRM as paramosh mentioned but I can't see anything that jumps out at me.
Thanks for all your responses. I did the following workaround.
Make a query that retrieve a list of all the Student enrollments
Use the Find method of the List<T> class to find if a record exist with the conditions I am searching for.
var query2 = (from e in svsContext.xrmsm_sessionEnrollmentsSet
join s in svsContext.xrmsm_sessionsSet on e.xrmsm_SessionLookup.Id equals s.xrmsm_sessionsId
join ic in svsContext.xrmsm_institutionCoursesSet on s.xrmsm_institutionCourseLookup.Id equals ic.xrmsm_institutionCoursesId
join ts in svsContext.xrmsm_term_sessionsSet on e.xrmsm_termSessionLookup.Id equals ts.xrmsm_term_sessionsId
join t in svsContext.xrmsm_termsSet on ts.xrmsm_TermLookup.Id equals t.xrmsm_termsId
where (e.xrmsm_StudentLookup.Equals(studentlookup))
select new
{
EnrollmentId = e.xrmsm_sessionEnrollments_id,
SessionId = s.xrmsm_sessions_id,
EnrollmentYear = e.xrmsm_YearLookup,
InstitutionCourseId = (Guid)ic.xrmsm_institutionCoursesId,
TermId = (Guid)t.xrmsm_termsId,
Student = e.xrmsm_StudentLookup
}).ToList();
var q = query2.Find(r => r.EnrollmentYear.Id == entity.GetAttributeValue<EntityReference>("xrmsm_yearlookup").Id
&& r.InstitutionCourseId == institutionCourseGuid
&& r.TermId == termGuid);

LINQ/LinqPad: same query different results

So we copy and paste the exact same query from LinqPad into our EF 4.3 application, pointed at the exact same database and get a different result. In LinqPad we get 2 records returned. In our application we reaise an error "Object reference not set to an instance of an object."
var Shippings = shippingRepository.All.ToArray();
var SalesOrderHeaders = salesOrderHeaderRepository.All.ToArray();
var Customers = customerRepository.All.ToArray();
var Stores = storeRepository.All.ToArray();
var Departments = departmentRepository.All.ToArray();
var toShip = from sh in Shippings
join h in SalesOrderHeaders on sh.OrderId equals h.SalesOrderHeaderId
join c in Customers on h.CustomerId equals c.CustomerId
join st in Stores on h.StoreId equals st.StoreId
join d in Departments on h.DepartmentId equals d.DepartmentId into outer
from o in outer.DefaultIfEmpty()
select new
{
OrderId = sh.OrderId,
CustomerName = c.Name,
StoreName = st.Name,
DepartmentName = (o.Name == null) ? o.Name : "None",
DeliveryDate = h.DeliveryDateTime
};
In the application code, when we remove the outer join (to add Departments) and it's associated field the query returns the same 2 records asn in LinqPad.
Does anyone have any insight into how to fix this feature?
Click on "Add a connection" in linqpad and select datacontext from assembly like
You can choose Entity Framework datacontext or Entity Framework BDContext with POCO depending upon your scenario. click next and provide path to the assembly along with connection string and you will be good to go.
In LINQPad are you actually querying against your entity model? Take a look at this link if you aren't. I had a similar problem when starting out and didn't realize I had set up a default LINQ to SQL connection earlier and was querying against that.

Distinct works on IQueryable but not List<T>?? Why?

First Table is the View and Second is the result I want
This below query works fine
List<BTWStudents> students = (from V in db.vwStudentCoursesSD
where classIds.Contains(V.Class.Value)
select new BTWStudents
{
StudentId = V.StudentId
Amount= V.PaymentMethod == "Cashier Check" ? V.Amount: "0.00"
}).Distinct().ToList();
But I changed it to List to add string formatting(see below)
List<BTWStudents> students = (from V in db.vwStudentCoursesSD
where classIds.Contains(V.Class.Value)
select new {V}).ToList().Select(x => new BTWStudents
{
StudentId = V.StudentId
Amount= V.PaymentMethod == "Cashier Check" ? String.Format("{0:c}",V.Amount): "0.00"
}).Distinct().ToList();
With this Second Query I get this
Why is distinct not working in the second query?
When working with objects (in your case a wrapped anonymous type because you are using Select new {V} rather than just Select V), Distinct calls the object.Equals when doing the comparison. Internally, this checks the object's hash code. You'll find in this case, the hash code of the two objects is different even though the fields contain the same values. To fix this, you will need to override Equals on the object type or pass a custom IEqualityComparer implementation into the Distinct overload. You should be able to find a number of examples online searching for "Distinct IEqualityComparer".
Try this (moved your distinct to the first query and corrected your bugged if/then/else):
List<BTWStudents> students = (from V in db.vwStudentCoursesSD
where classIds.Contains(V.Class.Value)
select new {V}).Distinct().ToList().Select(x => new BTWStudents
{
classId = V.Class.HasValue ? V.Class.Value : 0,
studentName = V.StudentName,
paymentAmount = V.PaymentMethod == "Cashier Check" ? String.Format("{0:c}",x.V.AmountOwed): "0.00"
}).ToList();
You can get around using Distinct all together if you Group by StudentID
var studentsGroupedByPayment =
(from V in db.vwStudentCoursesSD
where classIds.Contains(V.Class.Value)
group V by V.StudentId into groupedV
select new
{
StudentID = groupedV.Key,
Amount = string.Format("{0:C}",
groupedV.First().PaymentMethod == "Cashier Check" ?
groupedV.First().Amount : 0.0)
}
).ToList();

Resources