Reputation: 504
In my .NET Winforms application, I have created Models using Database-First approach with Entity Framework from SQL Server. I have a combobox (cb2) that displays locations as its DataSource. The combobox's SelectedValue holds the LocationId. Now, I want to retrieve every Shift in Shifts where the location matches the selected Location in the combobox.
Models:
public partial class Location
{
public Location()
{
AktiveSchichten = new HashSet<AktiveSchichten>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<AktiveSchichten> AktiveSchichten { get; set; }
}
public partial class Shifts
{
public int Id { get; set; }
public TimeSpan Start { get; set; }
public TimeSpan End { get; set; }
public int Location { get; set; }
public virtual Location LocationNavigation { get; set; }
}
Now combobox cb2 has Location as Datasource.
public partial class Location
{
public Location()
{
AktiveSchichten = new HashSet<AktiveSchichten>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<AktiveSchichten> AktiveSchichten { get; set; }
}
In my attempt to query Shifts based on the selected Location from the combobox, I used the following code:
var shifts = dbContext.AktiveSchichten.Where(a => a.Location = cb2.SelectedValue);
foreach (var shift in shifts)
{
//..
}
However, I encountered an error. I then modified my approach by explicitly converting the SelectedValue to an int as follows:
var shifts = dbContext.Shifts.Where(a => a.Location == (int)cb2.SelectedValue);
foreach (var shift in shifts)
{
//...
}
I'm curious to understand why using an int comparison in the second approach works while the first approach throws an error. What is the correct way to query Shifts based on the selected Location from the combobox?
Any insights would be appreciated. Thank you!
Upvotes: 2
Views: 143
Reputation: 941
Your approach is syntactically incorrect: you have an assignment in the Where
clause
a.Location = cb2.SelectedValue
instead of a comparison
a.Location == cb2.SelectedValue
and you're not casting cb2.SelectedValue
to an int (compared to the working statement var shifts =...
).
Contrary to jdweng's comment casts will work with with LINQ - as long as the cast is valid (cb2.SelectedValue
is of type object
and holds an int). But you might be better off to assign the value before the LINQ statement:
var locationId = (int)cb2.SelectedValue;
var shifts = dbContext.Shifts.Where(a => a.Location == locationId);
Furthermore: Do you really have AktiveSchichten
and Shifts
on your dbContext
? Maybe you would like to consolidate your naming (German, English; plural or singular for classes; class name for a property not representing an instance of the class Shifts.Location
) to make your code easier to understand.
Upvotes: 1