C# 在类中创建类并从数据库返回数据
我在一个类中创建了一个类,因此它可以作为编写3个不同方法调用 到数据库-所以我创建了一个包含相关项的类,现在当我尝试构建时,我得到了错误C# 在类中创建类并从数据库返回数据,c#,C#,我在一个类中创建了一个类,因此它可以作为编写3个不同方法调用 到数据库-所以我创建了一个包含相关项的类,现在当我尝试构建时,我得到了错误 无法将System.collections.generic.list类型隐式转换为我创建的StudentDocuments类 当我点击错误时,它会将我引向returnsubs语句 public class StudentDocuments { public Guid DocID {get; set;} public s
无法将System.collections.generic.list类型隐式转换为我创建的StudentDocuments类
当我点击错误时,它会将我引向returnsubs
语句
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;
}
}
您可以创建匿名类型的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)
您可以创建匿名类型的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)
谢谢,我认为这会起作用,但现在它告诉我,我无法将类型iqueryable studentDocument隐式转换为列表,并且我可能会丢失一个强制转换。另外,您可能需要考虑让
GetStudentSubmissionGrid
函数返回IEnumerable
,而不是返回列表。这样做的好处是,如果您进一步使用LINQ来选择较小的列表,它将节省一些数据库工作。(但与回答问题完全无关)。@Colindebean考虑并将List
更改为IEnumerable
,感谢您的解释。@HamletHakobyan感谢您的帮助-非常感谢!谢谢,我认为这会起作用,但现在它告诉我,我无法将类型iqueryable studentDocument隐式转换为列表,并且我可能会丢失一个强制转换。另外,您可能需要考虑让GetStudentSubmissionGrid
函数返回IEnumerable
,而不是返回列表。这样做的好处是,如果您进一步使用LINQ来选择较小的列表,它将节省一些数据库工作。(但与回答问题完全无关)。@Colindebean考虑并将List
更改为IEnumerable
,感谢您的解释。@HamletHakobyan感谢您的帮助-非常感谢!