在我的网站上,我试图返回一个列表,其中显示当前用户正在关注的用户,但我一直在收到错误Cannot implicitly convert type 'System.Collections.Generic.List' to 'string'
任何帮助都会很棒
用户控制器
public ActionResult Index()
{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var currentUser = manager.FindById(User.Identity.GetUserId());
return View(new Followuser()
{
User1ID = db.Followusers.Where(u => u.User1ID == currentUser.Id).ToList()
});
}
关注用户模型
public class Followuser
{
[Key, Column(Order = 0)]
public string User1ID { get; set; }
[Key, Column(Order = 1)]
public string User2ID { get; set; }
}
答案 0 :(得分:4)
你没有明显的原因打电话给ToList
。如果您将查询移出return语句,它也会使事情变得更清楚。打破你的代码,你有效地得到了:
// We're not certain what type `db.Followusers` is, to be honest.
List<Foo> list = db.Followusers.Where(u => u.User1ID == currentUser.Id)
.ToList();
Followuser user = new Followuser() { User1ID = list };
return View(user);
你看到那个中间陈述没有意义吗?
我怀疑你只想要以下内容,假设db.Followusers
真的像IQueryable<Followuser>
:
// Single checks that there's exactly one record matching the predicate.
Followuser user = db.Followusers.Single(u => u.User1ID == currentUser.Id);
return View(user);
或者鉴于它现在相当简短:
return View(db.Followusers.Single(u => u.User1ID == currentUser.Id));