5 框架,不在数据库中使用关系外键,我想知道 4.0 如何改进我需要在多个表连接后传回多个对象的代码垃圾。
public IList<User> GetTutorByCourseId(int courseId)
{
IList<User> output = new List<User>();
using (leDataContext db = new leDataContext())
{
try
{
var m = from c in db.Courses
join ct in db.CourseByTutors on c.Id equals ct.CourseId
join u in db.Users on ct.TutorId equals u.Id
where c.Id == courseId
select new
{
c, ct, u
};
foreach (var result in m)
{
User user = new User();
user.Id = result.u.Id;
user.Name = result.u.Name;
user.CourseTutor.Id = result.ct.Id;
user.Course.Name = result.c.Name;
output.Add(user);
}
return output;
}
catch (Exception ex)
{
Logger.Error(typeof(User), ex.ToString());
throw;
}
}
}
在 GUI 中有 3 个对象被返回给调用者。但是,要做到这一点,我必须在 User 类中添加 public CourseByTutors{get;set} 和 public Course(get;set;) 的属性,我发现这会弄乱我的代码。这种情况下,4.0怎么解决呢?我读了一些关于 select tupel .. ??
最佳答案
这个(在 3.5 中)怎么样?
select new User
{
Id = u.Id,
Name = u.Name,
CourseTutor = new CourseTutor {Id = ct.Id},
Course = new Course {Name = c.Name}
};
return m.ToList();
编辑:替换了非法的 CourseTutor.Name
和 Course.Id
初始值设定项。假设 User
的构造函数没有对 CourseTutor
和 Course
进行任何花哨的初始化,修正后的代码将起作用。
关于c# - 3.5 VS 4.0 .NET 框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5133880/