RIA Services: Entity Framework Reference Entities

2019-07-25 18:26发布

问题:

I'm attempting to use RIA services with a Entity Framework back end. The Model was auto generated by the designer. (VS 2010, .NET 4.0, EF 4.0, SilverLight 4.0) The issue that I'm running into is that Reference Properties are being loaded as expected at the Service Layer, but when that information is passed over to the SilverLight App the Reference Entity becomes NULL.

I've used two approaches to populating the Reference Entity:

public Employee GetEmployeeByID(int employeeID)
  {
   var result = this.ObjectContext.Employees
    .Include("EmployeeRoles")
    .Where(emp => emp.EmployeeID == employeeID)
    .FirstOrDefault();
   return result;
  }

And

public Employee GetEmployeeByID(int employeeID)
  {
   var result = this.ObjectContext.Employees
    .Where(emp => emp.EmployeeID == employeeID)
    .FirstOrDefault();

   if (result != null && result.EmployeeRoleReference.IsLoaded == false)
   {
    result.EmployeeRoleReference.Load();
   }
   return result;
  }

Both methods appear to correctly populate the Reference objects when examining the objects prior to the return. However when I attempt to reference the Employee Object from the UI via RIA Services, the EmployeeRole referenced entity is NULL.

On the Front End I'm calling:

public void LoadEmployeeProfile()
  {
   int empID = WebContext.Current.User.EmployeeID;
   LoadOperation<Employee> loadEmployee = _appcontext.Load(_appContext.GetEmployeeByIDQuery(empID));
   loadEmployee.Complete += new System.EventHandler(loadEmployee_Completed);
  }

  void LoadEmployee_Completed(object sender, System.EventArgs e)
  {
   LoadOperation<Employee> loadEmployee = sender as LoadOperation<Employee>;
   if (loadEmployee == null)
    return;

   loadEmployee.Completed -= LoadEmployee_Completed;
   foreach (Employee employee in loadEmployee.Entities)
   {
    this.EmployeeProfile == employee;
    break;
   }
  }

This appears to be all textbook type stuff, but I haven't been able to chase down a lead as to why the RIA services isn't populating the Reference entity as I would have expected it too.

回答1:

To clarify, you are trying to request an Employee record and include EmployeeRoles as defined by referential links in the database/Entity Model.

In the .Web RIA project that contains the metadata for Employee, I would check that you have marked EmployeeRoles in your Employee metadata with the [Include] attribute.

You need to include the references in your query and in the model metadata.

Hope this helps.