Linq查询并不能隐式转换类型错误

时间:2014-08-19 10:51:53

标签: asp.net linq asp.net-mvc-4

根据给定的项目ID(此id将作为参数进行操作),我想找到这个项目和这个项目的问题,然后我想找到一些有&#34; bug& #34;在我的MVC asp.net Web应用程序中使用linq查询键入。但是当我在ProjectController中的操作中尝试下面的代码时,我会收到此错误:无法隐式转换类型'System.Collection.Generic.List<System.Collections.Generic.List<MVCTest1.Models.Issue>>'to 'System.Collections.Generic.List<MVCTest1.Models.Issue>'

        List<Issue> issueList = (from i in db.Projects where i.projectID == projectId select i.Issues).ToList();

        List<Issue> bugList = (from bug in issueList where bug. ) --> I cannot reach properties of bug issue

这是我的项目模型:

  public class Project
  {

    public int projectID { get; set; }

    public string projectName { get; set; }

    public string descriptionProject { get; set; }

    public Project parentProject { get; set; }

    public string identifier { get; set; }


    public DateTime date { get; set; }

    public List<Project> subProjects { get; set; }

    public virtual List<Issue> Issues { get; set; }     
  }

和我的问题模型:

 public class Issue
 {
    public int issueID { get; set; }

    public string description { get; set; }

    public string subject { get; set; }

    public IssueStatus? status { get; set; }

    public Issue parentTask { get; set; }


    public DateTime startDate { get; set; }

    public DateTime dueDate { get; set; }

    public int done { get; set; }

    public IssuePriority? priority { get; set; }

    public IssueType? type { get; set; }

    public virtual List<User> Users { get; set; }

  }

最后我的枚举:

public enum IssueType
{
    Bug = 0,
    Feature = 1,
    Support = 2,
    Operation = 3
}

提前致谢。

//编辑2

        var project = db.Projects.Single(p => p.projectID == projectId);
        var issues = project.Issues;
        var bugIssues = from bug in issues where bug.type == 0 select bug;
        return PartialView(bugIssues);

当我写这篇文章时,我收到了这个错误:

传入字典的模型项的类型是&#39; System.Linq.Enumerable + WhereListIterator 1[MVCTest1.Models.Issue]', but this dictionary requires a model item of type 'System.Collections.Generic.List 1 [MVCTest1.Models.Issue]&#39;。

2 个答案:

答案 0 :(得分:0)

问题是,您的Issues媒体资源已经一个List<Issue>。我怀疑你想要的东西:

// TODO: Fix property naming...
var project = db.Projects.Single(p => p.projectId == projectId);
var issues = project.Issues;

现在issues将是List<Issue>而不是List<List<Issue>>

编辑:对于下一个问题,您有一个IEnumerable<Issue>,但您期望List<Issue>,因此您需要在上致电ToList() 点。例如:

var project = db.Projects.Single(p => p.projectId == projectId);
return PartialView(project.Issues.Where(b => b.type == 0).ToList());

答案 1 :(得分:0)

问题在于MVC视图的预期模型,它期望System.Collections.Generic.List<T>,但您提供了System.Linq.Enumerable

尝试这样做。

return PartialView(bugIssues.ToList());