c# - 3.5 VS 4.0 .NET 框架

标签 c# linq frameworks

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.NameCourse.Id 初始值设定项。假设 User 的构造函数没有对 CourseTutorCourse 进行任何花哨的初始化,修正后的代码将起作用。

关于c# - 3.5 VS 4.0 .NET 框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5133880/

相关文章:

c# - 使用 jQuery.ajax() 时,HttpListener 仅获取 InputStream 的前 900 个字节

c# - 限制文件上传,以便只能上传小于 1 MB 的文件

c# - 分组然后展平项目

c# - LINQ C#的编写方法

ios - 构建 iOS .framework,其中包含适用于所有架构的 PLCrashReporter 依赖项目

macos - 使用 LLDB 在剥离的二进制文件中设置断点

c# - 是否可以导出(伪造)内存中 MemoryStream 文件的位置路径?

c# - 为什么我不能将类隐式转换为其通用基类?

c# - 如何对所有者 == 当前用户的实体计数进行 LINQ 查询?

XCode - 将目标移动到不同的项目