Query DTO objects through WCF with linq to sql backend

后端 未结 3 812
臣服心动
臣服心动 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 16:55

    If you have long complicated entities then creating a projection by hand is a nightmare. Automapper doesn't work because LINQ cannot use it in conjunction with IQueryable.

    This here is the perfect solution : Stop using AutoMapper in your Data Access Code

    It will generate a projection 'magically' for you and enable you to run an oData query based on your DTO (data transfer object) class.

        [Queryable]
        public IQueryable GetDatabaseProductDTO(ODataQueryOptions options)
        {
            // _db.DatabaseProducts is an EF table 
            // DatabaseProductDTO is my DTO object
            var projectedDTOs = _db.DatabaseProducts.Project().To();
    
            var settings = new ODataQuerySettings();
            var results = (IQueryable) options.ApplyTo(projectedDTOs, settings);
    
            return results.ToArray().AsQueryable();
        }
    

    I run this with

    /odata/DatabaseProductDTO?$filter=FreeShipping eq true
    

    Note: this article is from a couple years ago and it's possible that by now AutoMapper has functionality like this built in. I just don't have time I check this myself right now. The inspiration for the above referenced article was based on this article by the author of AutoMapper itself - so it's possible some improved version of it is now included. The general concept seems great and this version is working well for me.

提交回复
热议问题