Reputation: 2143
ok, i have to admit that until now i still do not know the best way to return multiple objects using linq to sql.
public IList<Course> GetAllStudentCourses()
{
IList<Course> output = new List<Course>();
using (lenDataContext db = new lenDataContext())
{
var result =
from ct in db.CourseByTutors
join c in db.Courses on ct.CourseId equals c.Id
join u in db.Users on ct.TutorId equals u.Id
select new
{
c,
u,
};
foreach (var r in result)
{
Course course = new Course();
course.CourseByTutor = new CourseByTutor();
course = r.c;
course.IsGroupString = (r.c.IsGroup == 1) ? "Yes" : "No";
course.User = r.u;
output.Add(course);
}
}
return output;
}
I would like to return Course and User objects back to UI.
private void InitializeData()
{
Course c = new Course();
dgCourses.AutoGenerateColumns = false;
bs.DataSource = c.GetAllStudentCourses().ToList();
dgCourses.DataSource = bs; //bs is bindingsource
}
How do i display the user data e.g. Name to the Gridview? i have put User.Name to the datapropertyName but it still showing nothing. my Course.User has value.
Upvotes: 1
Views: 1010
Reputation: 3636
You can flatten your object by wrapping them in another object :
public class CourseDisplay
{
private Course course;
public CourseDisplay(Course course)
{
this.course = course;
}
public string CourseName
{
get { return course.Name; }
}
public string UserName
{
get { return course.User.Name;}
}
}
It is simpler to bind to a child property in ObjectListView.
Upvotes: 0
Reputation:
If you return db.CourseByTutors you should have access to both the users and the courses. The two inner joins you are doing above seem unessecary because you should be able to access them via EntitySet. Just use the navigation properties to access all the users and courses.
public IQueryable<CourseByTutors> GetAllStudentCourses()
{
lenDataContext db = new lenDataContext();
return db.CourseByTutors;
}
Then in your gridview you can reference the properties by Coures.property and Users.property on a databound column. You can't use a using statement though because as soon as you return the IQueryable you would dispose of the datacontext.
Upvotes: 1