I realized that for some odd reason you can't chain the .Where() after the .Select(), so I came up with this.
var eventCalendar = db.EventCalendars.Where(q => q.Date == e.Day.Date);
if (!isLogged)
{
eventCalendar = eventCalendar.Where(q => q.ClientFlag == true);
}
eventCalendar = eventCalendar.Select(q => q.EnvironmentId).Distinct();
but now I get and error at the .Select
"Cannot implicitly convert type 'System.Linq.IQueryable<short>' to 'System.Linq.IQueryable<IT_Portal.EventCalendar>'. An explicit conversion exists (are you missing a cast?)"
What am I doing wrong? To put it simply, I just want to be able to grab Distinct Environment ID from the Calendar Event table so that I can notify users if there is an event occurring that day on a specific environment. Finally if the user is not logged in, get only Environment Id from events that are marked to be displayed for client (ClientFlag).
Your last line is the problem. You're trying to re-use a local variable that is a different type than you're assigning to it. You just need to change it slightly:
var eventCalendarEnvironmentIds =
eventCalendar.Select(q => q.EnvironmentId).Distinct();
You need a new variable.
var environmentIDs = eventCalendar.Select(q => q.EnvironmentId).Distinct();
By selecting Select(q => q.EnvironmentId) you are actually selecting the EnvironmentId and not the eventCalenderObject.
Try changing:
var eventCalendar = db.EventCalendars.Where(q => q.Date == e.Day.Date);
to:
// I specify IQueryable, you can use 'var' - you simply need to change the variable name
IQueryable eventQuery = db.EventCalendars.Where(q => q.Date == e.Day.Date);
Then, selecting:
var eventCalendar = eventQuery.Select(q => q.EnvironmentId).Distinct();
Sometimes, when you continue to use var, you may lose sight of the data type. You should use the actual data type as often as you can. Getting caught in the trap of using var is not a good practice, IMO.
Related
Hi All I am trying to do below ,I want to load an attribute value like this .
var date = db.GetTable<bbb>().Where(x => idList.Contains(x.MID))
.Select(x => x.ModifiedDate).FirstOrDefault;
var test = db.GetTable<nnn>().Where(x => xguy.Distinct().Contains(x.SID))
.LoadWith(x => x.Modified == lastPostDate);
exception:-
LinqToDB.LinqToDBException: 'Expression '(x.Modified == value(vv.x+<>c__DisplayClass25_1).lastPostDate)' is not an association.'
How can I do this?
I used the FirstOrDefault option to get one value, but I do not understand about Expression is not an association.
Your use of the "LoadWith" method is suspicious here.
LoadWith is a specialized function to load additional table data that is linked (e.g. via foreign key) to the current table row.
Based on your usage, it looks like you're just trying to set up another "Where" clause, so instead of
.LoadWith(x => x.Modified == lastPostDate);
you wanted
.Where(x => x.Modified == lastPostDate);
or alternatively, combine this with your prior Where statement to simplify things:
var test = db.GetTable<nnn>().Where(x => x.Modified == lastPostDate &&
xguy.Distinct().Contains(x.SID));
Let me know if this isn't what you intended. If this is the case, perhaps you have an SQL statement or similar that you are now trying to translate to C# LINQ, or can otherwise explain in plain English what this statement was meant to accomplish?
This piece of code keep making this error. :
Unable to create a constant value of type 'Repository.DBModel.Subscriber'. Only primitive types or enumeration types are supported in this context.
I've Changed it a few times but it keeps coming up with this Error.
using (SubscriberDBHandler db = new SubscriberDBHandler())
{
IEnumerable <Subscriber> NewSubscribers = Subscribers
.Where(sub => db.Subscriber
.Any(aSub => !aSub.Email.Equals(sub.Email)));
List<Subscriber> updateSubscribers = db.Subscriber
.Where(dbSub => Subscribers
.Any(lSub => lSub.Email
.Equals(dbSub.Email))).ToList();
if(NewSubscribers.Count() >= 1)
{
db.Subscriber.AddRange(NewSubscribers);
}
updateSubscribers.ForEach(aSub => aSub.State = Subscribers
.FirstOrDefault(sub => sub.Email
.Equals(aSub.Email)).State ?? "Error" );
db.SaveChanges();
}
I'd greatly appreciate if someone could point out my error or come up with a more efficient way to do this.
In advance thanks for your time and help.
I know there are a few post with this error out there but when reading them I can't figure out how they relate to my problem. so I'm sorry if this is a common mistake and others have provided a solution
The object Subscribers is a List<Subscriber>
I don't seem to be able to find the line but. the stack trace does contain this.
at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source)
at Repository.SubScribRepository.AddOrUpdateSubscribers(List1 Subscribers)
You use a local collection, Subscribers, directly in a LINQ statement. But these objects can't be translated into SQL. There are only mappings from primitive types to database types.
I'd suggest you use
var emails = Subscribers.Select(s => s.Email).ToList();
And proceed by using these strings (i.e. primitive values) in Contains statements like:
var newSubscribers = db.Subscriber
.Where(dbSub => !emails.Contains(dbSub.Email))
.ToList();
var updateSubscribers = db.Subscriber
.Where(dbSub => emails.Contains(dbSub.Email))
.ToList();
Changing updateSubscribers to an IEnumerable will prevent this error
Im having some trouble writting a linq expression using entity framework. I have two related entities. Pago (payments) and Cuota(shares). In Cuota, I have the id_prestamo (loan id).
What I need is to get all the Pago(payments) for one Prestamo(loan). But as i have the Pago related only to Cuota, i have to get the id_prestamo from Cuota. The problem is that I cant navigate throw Cuota like this:
Lista_pagos = db.Pago.Where(x => x.Cuota.Prestamo.id_prestamo == prestamo.id_prestamo).ToList();
I tried also this expression but it doesnt work either:
Lista_pagos = db.Pago.Where(x => x.Cuota.Where(y => y.Prestamo.id_prestamo == prestamo.id_prestamo)).ToList();
When I say it doesn´t work is because I cannot compile the application. There must be an error in this place x.Cuota.Where(y => but don´t know how to use the where sentence right. I get this:
"The delegate does not take 1 argument"
Does anybody know how can i write this expression right?
I attach the entity relationship below.
Thanks!
You have a syntax error in your query.
db.Pago.Where()
...takes a predicate -- a function which returns bool.
x.Cuota.Where()
...returns IQueryable<Cuota>
So:
db.Pago.Where(x => x.Cuota.Where( ... ))
...is invalid code, because IQueryable<Cuota> is not bool.
I think what you actually want is:
Lista_pagos = db.Pago.Where(
x => x.Cuota.Any(y => y.Prestamo.id_prestamo == prestamo.id_prestamo)
).ToList();
(Note Any instead of Where.)
You have Cuotas for your Prestamos (by the way, Cuota is Installment, not Share, share is Acción) and you want all the Pagos for a given Prestamo:
Lista_Pagos = (from p in Pagos
join c in Cuotas
on p.Cuota.Cuota_Id equals c.Cuota_Id
where c.Prestamo.Prestamo_Id == prestamo.Prestamo_Id
select p).ToList<Pago>();
I have Items and Lines that are linked with the ItemsLines table.
On a web page, I show an item. I want to display in a DropDownList all Lines that are not linked to this Item.
This doesn't work :
int ItemId = Convert.ToInt32(Request.QueryString["id"]);
ddlLines.DataSource = context.Lines.Where(t => !t.ItemLines.Any(x => x.ItemId == ItemId));
I was trying to get the Lines where(they are not associated to the Item).
I can't figure out how to do this.
Thank you very much!
EDIT :
This is the error message I get:
the objectcontext instance has been disposed and can no longer be used
Your error is not because your lambda expression is incorrect. Your issue is that the context object you are using to connect to your database has already been disposed of before you call:
ddlLines.DataSource = context.Lines.Where(t => !t.ItemLines.Any(x => x.ItemId == ItemId));
The solution is to add a .ToList() to the end of your expression. This is because the .Where lambda expression returns something from the IQueryable interface and everything from that interface still has a connection to the database. So by adding .ToList() it will remove the connection to the database.
First, the error message is because the context has been disposed (I assume you are using it inside a 'using' block, which means the context has been disposed by the time the actual data binding occurs). If you intend to directly bind to the items, you may want to use projection, which will create a new instance that is not connected to the DataContext:
ddlLines.DataSource = context.Lines.Where(
t => !t.ItemLines.Any(x => x.ItemId == ItemId)
).Select(
t => new
{
SomeProperty = t.SomeProperty,
SomeOtherProperty = t.SomeOtherProperty }).ToList();
// Where SomeProperty and SomeOtherProperty are the display/value fields, etc.
Second, you might want to consider using Except for this instead of your lambda. It'll return an IEnumerable of all things NOT in the set you supply, and it's a bit cleaner:
ddlLines.DataSource = context.Lines.Except(new int[] { ItemId }).Select(...).ToList();
I have list of items contained in viewbag ViewBag.RoomBookings
As an example:
I want all the Roombookings with ViewBag.RoomBookings.RoomNo = 6 AND ViewBag.RoomBookings.Time < DateTime.Now AND ViewBag.RoomBookings.Time < DateTime.Now + 3600
Looping through is a NO.
And it must be done on the view, as I also need access to all the other roombookings too to populate a timetable.
Alternatively, Im thinking of Hash lists? Where I could list it with RoomNo, and Time and access it that way. But I cant find any good documentation on this if its even possible.
Ive tried a few things (just to test a method that works (these wont follow the same critera as above)):
var RoomBookingsTemp = ViewBag.RoomBookings;
var newlist = (from RoomOcc in RoomBookingsTemp where RoomOcc.EndDateTime < DateTime.Now select RoomOcc.RoomNo);
var bookings = RoomBookingsTemp.Where(roombooking => DateCheckStart < roombooking.EndDateTime && DateCheckEnd > roombooking.StartDateTime && roombooking.RoomNo == RoomNo);
var newlist = RoomBookingsTemp.Select(m => m["RentalNo"]);
But none are valid.
You need to cast the RoomBookingsTemp variable. When you declare it directly from the ViewBag it's still a dynamic type [details about viewbag] and the error your seeing is that linq can't query/iterate over a dynamic type.
I'm not sure what type you're actually using but try something like this...
var RoomBookingsTemp = ViewBag.RoomBookings as List<RoomBooking>;
or
List<RoomBooking> RoomBookingsTemp = ViewBag.RoomBookings;
What's wrong with your second method? You are just missing the select.
// Some statements removed from where for clarity
var bookings = RoomBookingsTemp.Where(rb => rb.RoomNo == 6).Select(rb => rb);