Reputation: 791
I have a dropdown list which I pass to a view via a ViewBag:
ViewBag.RoomTypeID = new SelectList(db.RoomType, "ID", "Type");
This obviously works fine, but I want to do something a little more complex, and am struggling to find where to start.
Ultimately, I want the dropdown list to only show RoomTypes that haven't already been assigned (COUNT = 0) in a seperate table. My models are:
public class RoomType
{
[Key]
public int ID { get; set; }
[Display(Name = "Room Type")]
public string Type { get; set; }
public virtual ICollection<Room> Rooms { get; set; }
}
and...
public class Room
{
[Key]
public Guid ID { get; set; }
[Required]
public int PropertyID { get; set; }
[Required]
public int RoomTypeID { get; set; }
//other properties removed for brevity
public virtual RoomType RoomType { get; set; }
public virtual Property Property { get; set; }
}
Assuming my property ID is 100, I only want to show room types in the dropdown list, where there isn't a room with propertyID 100 with the same roomtype.
What I have tried to do is this:
ViewBag.RoomTypeID = new SelectList(db.RoomType.Where(r => r.ID = (db.Rooms.Where(r => r.PropertyID == 1))) , "ID", "Type");
But I think I need to convert to a list of int's?
Upvotes: 0
Views: 76
Reputation: 1976
I don't know if i understand well, but i think you just have to refactor your linq query, like this:
var propertyIdNotWanted = 100;
ViewBag.RoomTypeID = new SelectList(db.RoomType.Where(r => r.Rooms.All(room => room.PropertyID != propertyIdNotWanted )) , "ID", "Type");
Or you could look through Rooom
like this:
db.Room.Where(r => r.PropertyID != propertyIdNotWanted).Select(r => r.RoomType)
Upvotes: 2