我有一个我在控制器中使用的模型属性RegimeItemID
。但是,当我试图调用它时,它会给出一个它不存在的错误。我做错了什么?
控制器
public ActionResult ExerciseIndex(int? id, UserExerciseViewModel vmodel)
{
User user = db.Users.Find(id);
//user.RegimeItems = ChosenExercises();
UserExerciseViewModel model = new UserExerciseViewModel { AvailableExercises = GetAllExercises(), RequestedExercises = ChosenExercises(user, vmodel) };
//user.RegimeItems = db.RegimeItems.Find(model.SelectedExercise);
user.RegimeItems = model.RequestedExercises;
return View(model);
}
private List<RegimeItem> ChosenExercises(User user, UserExerciseViewModel model)//RegimeItem regimeItem)//User user, RegimeItem regimeItem)
{
return db.Users.Where(r => r.RegimeItems.RegimeItemID == user.UserID).ToList();
}
模型
public class User
{
public int UserID { get; set; }
public ICollection<RegimeItem> RegimeItems { get; set; }
public User()
{
this.RegimeItems = new List<RegimeItem>();
}
}
public class RegimeItem
{
public int RegimeItemID { get; set; }
public Exercise RegimeExercise { get; set; }
}
视图模型
public class UserExerciseViewModel
{
public List<Exercise> AvailableExercises { get; set; }
public List<RegimeItem> RequestedExercises { get; set; }
public int? SelectedExercise { get; set; }
public int[] AvailableSelected { get; set; }
public int[] RequestedSelected { get; set; }
public string SavedRequested { get; set; }
}
我收到错误:
'System.Collections.Generic.ICollection<Project.Model.RegimeItem>' does not contain a definition for 'RegimeItemID' and no extension method 'RegimeItemID' accepting a first argument of type 'System.Collections.Generic.ICollection<Project.Model.RegimeItem>' could be found (are you missing a using directive or an assembly reference?)
我在控制器的这一行上得到它:
return db.Users.Where(r => r.RegimeItems.RegimeItemID == user.UserID).ToList();
答案 0 :(得分:9)
RegimeItems
是RegimeItem
元素的集合 - 它不是单个元素,因此它没有单个ID。< / p>
听起来你可能想要这样的东西:
return db.Users
.Where(r => r.RegimeItems.Any(ri => ri.RegimeItemID == user.UserID))
.ToList();
这将找到具有任何政权项目的用户,其政权项目ID等于其用户ID。现在还不是很清楚这是否是明智的查询 - 为什么政权项目ID等于用户ID?它也没有正确的返回类型 - 这将返回User
s的列表,而不是RegimeItem
s。
你似乎更想要这样的东西:
return db.Users
.Where(u => u.UserID == user.UserID)
.SelectMany(u => u.RegimeItems)
.ToList();
或者可能:
return db.Users
.Where(u => u.UserID == user.UserID)
.Single()
.RegimeItems
.ToList();
(您应该查看每种情况下涉及的查询。)