Query DTO objects through WCF with linq to sql backend

后端 未结 3 811
臣服心动
臣服心动 2021-01-24 16:22

I am working on a project where we need to create complex queries against a WCF service.

The service uses linq to sql at the backend and projects queries to data transfe

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-24 17:11

    With OData services, you are not bound to return database entities directly. You can simply return any DTO in queryable format. Then with the help of LINQ's Select() method, you can simply convert any database entity into DTO just before serving the query:

    public class DataModel
    {
      public DataModel()
      {
        using (var dbContext = new DatabaseContext())
        {
          Employees = from e in dbContext.Employee
                      select new EmployeeDto
                      {
                        ID = e.EmployeeID,
                        DepartmentID = e.DepartmentID,
                        AddressID = e.AddressID,
                        FirstName = e.FirstName,
                        LastName = e.LastName,
                        StreetNumber = e.Address.StreetNumber,
                        StreetName = e.Address.StreetName
                      };
        }
      }
    
      /// Returns the list of employees.
      public IQueryable Employees { get; private set; }
    }
    

    You can now easily set this up as a OData service like this:

    public class EmployeeDataService : DataService
    

    For full implementation details, see this excellent article on the subject. OData services are actually very very powerful once you get the hand of them.

提交回复
热议问题