Search code examples
c#wpfcrystal-reportsodataasp.net-web-api2

How to handle One-to-Many relationship in OData Client?


I have a Web Api 2 Service and a WPF OData Client and I am working with Crystal Reports.

I have two tables( Teacher, Subject ) having One-to-Many relationship between them. I am trying to get Subjects against Teacher_Id.

Following is the code that I am using:

private string ServiceUri = "http://localhost:50623/odata";
    private void pge_TeacherReportPage_Loaded(object sender, RoutedEventArgs e)
    {
        var Container = new Default.Container(new Uri(ServiceUri));
        ReportDocument report = new ReportDocument();
        report.Load("../../TeacherCrystalReport.rpt");
        var Teacher = from c in Container.Teachers
                      select new
                      {
                         Name = c.Name,
                         FatherName = c.FatherName,
                         ContactNo = c.ContactNo,
                         Address = c.Address,
                         Religion = c.Religion,
                         CNIC = c.CNIC,
                         Status = c.Status,
                         UserName = c.UserName,
                         Subjects = c.Subjects.Where(s=> s.Teacher_Id == c.Teacher_Id).SingleOrDefault()
                      };
        report.SetDataSource(Teacher);            
        rpt_Teacher.ViewerCore.ReportSource = report;
    }

But I am unable to do so as I am getting the Following Exception:

An unhandled exception of type 'System.NotSupportedException' occurred in Microsoft.OData.Client.dll

Additional information: Constructing or initializing instances of the type <>f__AnonymousType1`9[System.String,System.String,System.String,System.String,System.String,System.String,System.String,System.String,QuizSystemClient.RestApiOData.Models.Subject] with the expression c.Subjects.Where(s => (s.Teacher_Id == c.Teacher_Id)).SingleOrDefault() is not supported.

Please tell me how can I resolve that?


Solution

  • My problem is solved, I had made the following changes in my code.

        var Teacher = from c in Container.Teachers
                          select new
                          {
                             Name = c.Name,
                             FatherName = c.FatherName,
                             ContactNo = c.ContactNo,
                             Address = c.Address,
                             Religion = c.Religion,
                             CNIC = c.CNIC,
                             Status = c.Status,
                             UserName = c.UserName,
                             //I had made changes in the following code:
                             Subjects = c.Subjects.Select(s=>s.Subject_Name).FirstOrDefault()
                          };