首页 \ 问答 \ ASP.NET Web API 2 - 从POST方法解析JSON以动态查询数据库(ASP.NET Web API 2 - Parsing JSON from a POST method to query database dynamically)

ASP.NET Web API 2 - 从POST方法解析JSON以动态查询数据库(ASP.NET Web API 2 - Parsing JSON from a POST method to query database dynamically)

我想公开我的数据库,以便可以将POST发送到我的控制器,然后用于构建查询。 我正在使用实体框架来构建我的数据上下文。 这里的想法是客户端会在POST主体中传递JSON。 从那里查询将使用JSON中指定的属性和值进行构建。 这里的踢球者是我不想硬编码值。 我希望以这种动态方式构建查询,以便对数据上下文所做的任何更改都将直接反映在代码中。

例如,我想:

[
    {
        "NAME":"Random Name"
    },
    {
        "NAME":"Random Name 2",
        "STATUS":"ACTIVE"
    }
]

要翻译成以下内容:

var query = FROM d in DataContext 
WHERE (x.NAME == "Random NAME 1") 
OR (X.NAME == "Random Name 2" AND X.STATUS == "ACTIVE")

请记住,可以选择超过60种可能的属性,并且数据模型可能会发生变化。

这是我的想法是将JSON解析为对象数组,循环遍历每个对象,然后遍历该对象的非空属性以动态构建查询。

这是我的代码与实际变量。

调节器

    public class AgreementsController : ApiController
    {

        private AgreementRepository agreementRepository;

        public AgreementsController()
        {
            this.agreementRepository = new AgreementRepository();
        }

        public AGREEMENT[] Post([FromBody]AGREEMENT[] Agreements)
        {

            return agreementRepository.PostAgreements(Agreements);
        }
    }

服务

public class AgreementRepository
    {
        private DataBaseEntities db = new DataBaseEntities();

        public AGREEMENT[] PostAgreements(AGREEMENT[] Agreements)
        {
            List<AGREEMENT> a = new List<AGREEMENT>();

            foreach (AGREEMENT agreement in Agreements)
            {
                /////Loop Through Possible Attributes and then 
                /////Build queries based off of non null values.
                ////Append to List and return Agreement[] to controller

            }

            var agmts = a.ToArray<AGREEMENT>();

            return agmts;
        }



    }

I would like to expose my database such that a POST can be made to my controller that would then be used to build a query. I am using entity framework to build my Data Contexts. The idea here is that the client would pass JSON in the POST body. From there queries will be build using the attributes and values specified in the JSON. The kicker here is that I do not want to hard code values. I would like this to build queries in such a dynamic way that any changes made to the data context will directly be reflected in the code.

For example I would like:

[
    {
        "NAME":"Random Name"
    },
    {
        "NAME":"Random Name 2",
        "STATUS":"ACTIVE"
    }
]

To translate to something like:

var query = FROM d in DataContext 
WHERE (x.NAME == "Random NAME 1") 
OR (X.NAME == "Random Name 2" AND X.STATUS == "ACTIVE")

Keeping in mind that there are over 60 possible attributes that could be chosen and the data model may change.

This my thinking is to parse the JSON into an object array, Loop through each object, and then loop through non null attributes of that object to dynamically build a query.

Here is my code with actual variables.

Controller

    public class AgreementsController : ApiController
    {

        private AgreementRepository agreementRepository;

        public AgreementsController()
        {
            this.agreementRepository = new AgreementRepository();
        }

        public AGREEMENT[] Post([FromBody]AGREEMENT[] Agreements)
        {

            return agreementRepository.PostAgreements(Agreements);
        }
    }

Service

public class AgreementRepository
    {
        private DataBaseEntities db = new DataBaseEntities();

        public AGREEMENT[] PostAgreements(AGREEMENT[] Agreements)
        {
            List<AGREEMENT> a = new List<AGREEMENT>();

            foreach (AGREEMENT agreement in Agreements)
            {
                /////Loop Through Possible Attributes and then 
                /////Build queries based off of non null values.
                ////Append to List and return Agreement[] to controller

            }

            var agmts = a.ToArray<AGREEMENT>();

            return agmts;
        }



    }

原文:https://stackoverflow.com/questions/48451164
更新时间:2022-01-12 08:01

最满意答案

您应该能够在转换中使用补间功能完成此操作。 补间函数将在转换的每个滴答上触发,并且是每个滴答调用函数的一种方法。

补间方法需要一个属性名称(因为它旨在为属性提供自定义插值),但这可以是虚拟属性,也可以是未更改的属性(如下面的示例所示)。 有关方法的文档在这里

在我的示例中,我使用补间函数在屏幕上移动时拉出圆圈的x属性(井,cx属性):

 .tween("attr.fill", function() {
        var node = this;
        return function(t) { 
         console.log(node.getAttribute("cx"));
        }
      })

以下是工作中的一小段内容:

var svg = d3.select("body").append("svg")
  .attr("width",400)
  .attr("height",400);
  
var circle = svg.append("circle")
  .attr("cx",20)
  .attr("cy",20)
  .attr("r",10);
 
circle.transition()
  .attr("cx",380)
  .attr("cy",20)
  .tween("attr.fill", function() {
    var node = this;
    return function(t) { 
     console.log(node.getAttribute("cx"));
    }
  })
  .duration(1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.5.0/d3.min.js"></script>


You should be able to accomplish this using a tween function in your transition. A tween function will trigger on every tick of the transition and is one way to call a function every tick.

The tween method needs an attribute name (as it is intended to provide custom interpolation for an attribute), but this can be a dummy attribute, or one that isn't changed (as in my example below). Documentation on the method is here.

In my example I pull the x property (well, cx property) of a circle as it moves across the screen, using a tween function:

 .tween("attr.fill", function() {
        var node = this;
        return function(t) { 
         console.log(node.getAttribute("cx"));
        }
      })

Here is a snippet of it at work:

var svg = d3.select("body").append("svg")
  .attr("width",400)
  .attr("height",400);
  
var circle = svg.append("circle")
  .attr("cx",20)
  .attr("cy",20)
  .attr("r",10);
 
circle.transition()
  .attr("cx",380)
  .attr("cy",20)
  .tween("attr.fill", function() {
    var node = this;
    return function(t) { 
     console.log(node.getAttribute("cx"));
    }
  })
  .duration(1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.5.0/d3.min.js"></script>

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)