简体   繁体   English

创建动态DTO

[英]Create a dynamic DTO

Im trying to implement a dynamic dto. 我正在尝试实现动态dto。 First there will be a information manager where you can select the fields you want to return by the WebApi. 首先,将有一个信息管理器,您可以在其中选择要由WebApi返回的字段。

Later in the api you send a request to an endpoint with the DTO's Id you want. 稍后,您会在api中使用所需的DTO ID向端点发送请求。 This method will recive the info, query it in the db and obtain the fields that integrate the DTO(dynamic number of fields): 该方法将获取信息,在数据库中查询该信息,并获得集成DTO(动态字段数)的字段:

   [Route("api/workers")]
    public IEnumerable<object> GetWorkers([FromRoute] string idEnterprise,int idDTO)
    {
        //lstDummyFields = _context.Dtos.Include("DtoFields").
           //Where(n=>n.idDto==idDTO).select(n=>n.DtoFields.name).ToList();

        //The property will look like this, the selected dto could have different properties(dynamic) but always call the same as the entity name fields
        List<string> lstDummyFields = new List<string>
        {
            "idWorker",
            "first_name",
            "last_name",
            "birthday",
            "adress"
        };

        dynamic dto = new ExpandoObject() as IDictionary<string,object>;
        foreach (var p in lstDummyProperty)
        {
            dto.Add(p, null);
        }


        return _context.workers.Where(n=>n.IdEnterprise==idEnterprise).select.(new { ???? }) .ToList();
    }

I dont know how to implement the select clause.Could be related to this post but its sligtly different. 我不知道如何实现select子句。可能与这篇文章有关,但有明显的不同。

https://stackoverflow.com/a/34726946/2642777 https://stackoverflow.com/a/34726946/2642777

I'm close to the answer or im going the wrong way? 我接近答案还是我走错路了? Could throw some help to solve this please. 可以提供一些帮助来解决此问题。

We don't know your case, maybe use Directory is better? 我们不知道您的情况,也许使用Directory更好? But you can use this code: 但是您可以使用以下代码:

        List<string> lstDummyFields = new List<string>
        {
            "idWorker",
            "first_name",
            "last_name",
            "birthday",
            "adress"
        };

        dynamic dto = new ExpandoObject();
        foreach (var p in lstDummyFields)
        {
            ((IDictionary<String, Object>)dto).Add(new KeyValuePair<string, object>( p, null));
        }

Use Restier . 使用Restier It's a wrapper around OData (in 2 lines of code !) that means you can call the API with things like: 它是OData的包装(两行代码!),这意味着您可以使用以下方式调用API:

http://services.odata.org/v4/TripPinServiceRW/People?$top=2&$select=FirstName,LastName&$filter=Trips/any(d:d/Budget gt 3000)

Which is a dynamic query, filter, and field selection. 这是动态查询,过滤器和字段选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM