在类中创建类并从数据库返回数据

时间:2013-03-14 21:25:42

标签: c#

我在一个类中创建了一个类,因此它可以替代编写3种不同的方法调用           到数据库 - 所以我创建了一个相关项目的类,现在当我尝试构建我得到错误           Cannot implicity convert type System.collections.generic.list<anonymousType#1> to class that i created StudentDocuments           当我点击错误时,它会将我引导至return subs语句。

public class  StudentDocuments
    {
        public Guid DocID {get; set;}
        public string Assignment {get; set;}
        public DateTime Submitted {get; set;}
        public string Student {get;set;}
    }




public StudentDocuments GetStudentSubmissionGrid(Guid usr, Guid lib)
    {
        using (var dc = new DocMgmtDataContext())
        {
            var subs = (from doc in dc.Documents
                        join u in dc.Users on doc.OwnedByUserID equals u.ID
                        where doc.OwnedByUserID == usr && doc.LibraryID == lib
                        select new { 
                            DocID = doc.ID, 
                            Assignment = doc.Library.Name, 
                            Submitted = doc.UploadDT,
                            Student = u.FullName
                        })
                .OrderByDescending(c => c.Submitted).ToList();
            return subs;
        }
    }

1 个答案:

答案 0 :(得分:3)

您创建LINQ的匿名类型。相反,您必须根据返回类型创建特定类型对象列表。

使用此:

select new StudentDocuments{ 
                               DocID = doc.ID, 
                               Assignment = doc.Library.Name, 
                               Submitted = doc.UploadDT,
                               Student = u.FullName
                           }

并将您的方法声明为:

public List<StudentDocuments> GetStudentSubmissionGrid(Guid usr, Guid lib)

您也可以返回IEnumerable<StudentDocuments>而不是列表。

<强>更新

var subs = (from doc in dc.Documents
                    join u in dc.Users on doc.OwnedByUserID equals u.ID
                    where doc.OwnedByUserID == usr && doc.LibraryID == lib
                    orderby doc.UploadDT descending
                    select new StudentDocuments
                     { 
                        DocID = doc.ID, 
                        Assignment = doc.Library.Name, 
                        Submitted = doc.UploadDT,
                        Student = u.FullName
                     }).AsEnumerable().ToList();