In LinqPad
Getting the following error trying to union int? and int variables
Researched but can't find a solution that seems to work.
CS1929 'IQueryable<>' does not contain a definition for 'Union' and the best extension method overload 'ParallelEnumerable.Union<>(ParallelQuery<>, IEnumerable<>)' requires a receiver of type 'ParallelQuery<>'
//Parent not null
var parent =
from s in Students
where s.Id==5027
select new {
ID_PK = s.CaseOwnerIdAspnet_Users.User_ID_FKDYN_User_Profile.Organization_ID_FKDYN_Organization.Parent_ID_FK == null ?
s.CaseOwnerIdAspnet_Users.User_ID_FKDYN_User_Profile.Organization_ID_FKDYN_Organization.ID_PK
:
s.CaseOwnerIdAspnet_Users.User_ID_FKDYN_User_Profile.Organization_ID_FKDYN_Organization.Parent_ID_FK
};
var orgs =
from o in DYN_Organizations
join p in parent on o.Parent_ID_FK equals p.ID_PK
select new {ID_PK = o.ID_PK};
parent.Union(orgs);
Suppose parent is returning int? and orgs is returning int, then you can change orgs to return int? by casting the value, eg
change it to
var orgs =
from o in DYN_Organizations
join p in parent on o.Parent_ID_FK equals p.ID_PK
select new {ID_PK = (int?) o.ID_PK};
Your error message also mentions ParallelQuery and IEnumerable and I'm not sure if you can create a union between this types. If not, then the easiest way is to add .ToList() to the end of each query and then you are creating a union between two Lists which will work.
Related
I want to define a function containing a Linq query as bellow:
public IQueryable GetBasket(Guid userId)
{
DabbaghanDataContext db = new DabbaghanDataContext();
int rowNo = 0;
var query = (from c in db.Carts
join co in db.CartOrders on c.Id equals co.Cart_Id
join p in db.Products on co.Product_Id equals p.Id
where c.UserId == userId && c.Issued == false
select new
{
co.Quantity,
co.TotalPrice,
p.Code,
p.Price,
p.Thumbnail
}).AsEnumerable().Select(r => new
{
RowNumber = ++rowNo,
Quantity = r.Quantity,
TotalPrice = r.TotalPrice,
Code = r.Code,
Price = r.Price,
Thumbnail = r.Thumbnail
});
return query;
}
I get error
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Linq.IQueryable'.
on the return query line.
What is the problem? How can I solve this problem? Please help.
Your problem is the call to AsEnumerable- It converts the IQueryable to a IEnumerable; and therefore, you cannot return it as an IQueryable.
Correct me if I am wrong, but the second select seems to only add the row number to the result. You might as well want to do that together with the initial select, and skip the call to AsEnumerable().
Possible solutions: Rewrite the query to not use AsEnumerable (if you want an IQueryable returned), or you could change the return type to be IEnumerable, if that is a better fit for your problem.
In return query; change that to return query.AsQueryable();
And also try to change the method signature to use IQueryable instead of the nongeneric one
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();
I'm having issues with GROUP BY and eager loading. I try to explain what im doing.
I'm querying a datacontext ctx for events
The event class has the following properties
string Description
DateTime Date
bool IsDeleted
Guid SubjectId
string Title
DateTime Created
Guid ForProjectId
Person TriggeredBy
List<Guid> Targets
There are muttiple events with the same SubjectId and i would like to end up having events with unique SubjectIds and that are the newest in the group. I end up with the following query.
var events = from x in
(from e in ctx.Events
.Include("TriggeredBy")
.Include("Targets")
group e by e.SubjectId
into g
select new
{
GroupId = g.Key,
EventsWithSameSubjectId = g,
}
)
select x.EventsWithSameSubjectId
.OrderByDescending(y => y.Created).FirstOrDefault();
The query compile fine and returns the right resulting set. But the included properties are always null.
When i strip the query to see if eagor loading is working properly....
var events = (from e in ctx.Events.OfType<DataNotificationEvent>()
.Include("TriggeredBy")
.Include("Targets")
select e).ToList();
This return the events with all the included properties.
Is this a known issue / bug with Linq / EF or is there any way i can get rid of this error.
Regards
Vincent Ottens
You're projecting onto an anonymous type, so Include() isn't going to work like that. Because what you've done with the group and projecting into the anonymous type is to change the shape of the query. That tosses out the eager loading. Reading this article might help.
Thnx for the quick answer. You pointed me in the right direction. Here is the solution i came up with:
using MyFunc = Func<ExtendedCoreContext, Guid, IQueryable<DataNotificationEvent>>;
private static readonly MyFunc GetMentionsNewCompiledQuery =
CompiledQuery.Compile<ExtendedCoreContext, Guid, IQueryable<DataNotificationEvent>>(
(ctx, personId) => ((ObjectQuery<DataNotificationEvent>)(
from x in (
from e in ctx.Events.OfType<DataNotificationEvent>()
group e by e.SubjectId
into g
select g.OrderByDescending(p => p.Created).FirstOrDefault()
)
orderby x.Created descending
where x.Targets.Any(t => t.Id == personId)
select x
))
.Include(EntityProperties.Event.TriggeredBy)
.Include(EntityProperties.DataNotificationEvent.Targets)
);
I have an odd linq subquery issue.
Given the following data structure:
Parents Children
------- --------
Id Id
ParentId
Location
HasFoo
(obviously this is not the real structure, but it's close enough for this example)
I'm able to run this query and get a desired result:
bool b = (from p in Parents
from c in Children
where p.Id == 1 && c.ParentId == p.Id && c.Location == "Home"
select c.HasFoo).SingleOrDefault();
So if there is a child that has the Location "Home" for a Parent of Id 1, I will get that Child's "HasFoo" value, otherwise, I'll get false, which is the "default" value for a bool.
However, if I try and write the query so I have a list of Parent objects, like so:
var parentList = from p in Parents
select new ParentObject
{
ParentId = p.ParentId,
HasHomeChildren = p.Children.Count(c => c.Location == "Home") > 0,
HasHomeChildrenWithFoo = (from c in p.Children where c.Location == "Home" select c.HasFoo).SingleOrDefault()
}
I get the following error when iterating over the list:
The null value cannot be assigned to a member with type System.Boolean which is a non-nullable value type.
I don't see where this "null" value is coming from, however.
I wonder if the compiler is inferring HasHomeChildrenWithFoo to be bool, but then actually casting to a nullable bool (thus messing up your SingleOrDefault call). At any rate, I'd be willing to bet you could fix it with a cast to a nullable type in that final select which you can then manually default to false when null. It'd probably make the error go away, but it's kind of a brute-force kludge.
var parentList = from p in Parents
select new ParentObject
{
ParentId = p.ParentId,
HasHomeChildren = p.Children.Any(c => c.Location == "Home"),
HasHomeChildrenWithFoo = (from c in p.Children where c.Location == "Home" select (bool?)c.HasFoo) ?? false)
}
Assuming that we have the following table:
Person:
PersonID,
Name,
Age,
Gender
And we are providing a search function that allows users to search the table according to the name and/or the age.
The tricky part in writing the SQL ( or LINQ) query is that the users can choose to search for both field, or any one field, or no field. If he wants to search for all then he would just have to leave the textbox blank.
The logic to do this can be written as follows:
var p;
if(Name_TextBox=='')
{
p=from row in person
select row ;
}
else
{
p= from row in person
where row.Name=Name_TextBox
select row ;
}
// repeat the same for age
Now after a while the code gets very long and messy... How can I compress the above into a single query with no if-else?
Try code like this
string personName = txtPersonName.Text;
int personAge = Convert.ToInt32(txtAge.Text);
var opportunites = from p in this.DataContext.Persons
select new
{
p.PersonID,
p.Name,
p.Age,
p.Gender
};
if (personsID != 0)
opportunites = opportunites.Where(p => p.PersonID == personID);
if (personName != string.Empty)
opportunites = opportunites.Where(p => p.Name.StartsWith(personName));
if (personAge != 0)
opportunites = opportunites.Where(p => p.Age == personAge);
This will work fine. If personName is not given it will be not add to where, and if given then it will added.
One alternative which I have used in SQL which could be implemented in Linq too is
var p = from p in Person
where p.Name == Name_TextBox || Name_TextBox == String.Empty
select p;
(Note that your 'linq' is using SQL syntax, which won't compile. Also you can't declare a var as you are doing without directly assigning a value)
why not use the null coalescing operator? eg.
var products = from a in context.products
where a.ID == (productID ?? a.ID)
select a;
This works really well on my system