将用户筛选的查询参数存储在数据库表中的最佳方法是什么?

leo*_*ora 6 asp.net-mvc database-design database-schema query-string

我有一个ASP.NET MVC网站.在我的后端,我有一个名为People以下列的表:

  1. ID
  2. 名称
  3. 年龄
  4. 地点
  5. ......(其他一些小组)

我有一个通用的网页,使用模型绑定来查询这些数据.这是我的控制器动作:

public ActionResult GetData(FilterParams filterParams)
{
      return View(_dataAccess.Retrieve(filterParams.Name, filterParams.Age, filterParams.location, . . .)
}
Run Code Online (Sandbox Code Playgroud)

映射到这样的东西:

 http://www.mysite.com/MyController/GetData?Name=Bill .. . 
Run Code Online (Sandbox Code Playgroud)

dataAccess层只是检查每个参数以查看它是否已填充以添加到db where子句.这非常有效.

我现在希望能够存储用户的过滤查询,我试图找出存储特定过滤器的最佳方法.由于某些过滤器在queryString中只有一个参数,而其他过滤器在过滤器中有10个以上的字段,因此我无法找到将此查询"过滤信息"存储到我的数据库中的最优雅方法.

我能想到的选择是:

  1. 有一个完整的表复制(有一些额外的cols),但称之为PeopleFilterQueries并在每个记录中填充一个FilterName并将过滤器的值放在每个字段(名称等)中

  2. 存储一个只有FilterName的表和一个字符串,我存储实际的查询字符串Name = Bill&Location = NewYork.这样,如果过滤器更改或增长,我将不必继续添加新列.

这种情况的最佳做法是什么?

Tr1*_*tan 6

如果目的是保存最近使用的过滤器列表,我会在模型绑定发生后将完整的FilterParams对象序列化为XML字段/列.通过将其保存到XML字段中,您还可以灵活地使用XQuery和DML,以便日后能够以更高性能为重点查询信息.

    public ActionResult GetData(FilterParams filterParams)
    {
          // Peform action to get the information from your data access layer here
          var someData = _dataAccess.Retrieve(filterParams.Name, filterParams.Age, filterParams.location, . . .);

          // Save the search that was used to retrieve later here
          _dataAccess.SaveFilter(filterParams);
          return View(someData);
    }
Run Code Online (Sandbox Code Playgroud)

然后在您的DataAccess类中,您将需要两个方法,一个用于保存,另一个用于检索过滤器:

public void SaveFilter(FilterParams filterParams){
    var ser = new System.Xml.Serialization.XmlSerializer(typeof(FilterParams));
    using (var stream = new StringWriter())
           {
              // serialise to the stream
              ser.Serialize(stream, filterParams);
           }
  //Add new database entry here, with a serialised string created from the FilterParams obj
  someDBClass.SaveFilterToDB(stream.ToString());
}
Run Code Online (Sandbox Code Playgroud)

然后,当您想要通过Id检索已保存的过滤器时:

public FilterParams GetFilter(int filterId){

      //Get the XML blob from your database as a string
      string filter = someDBClass.GetFilterAsString(filterId);

      var ser = new System.Xml.Serialization.XmlSerializer(typeof(FilterParams));

      using (var sr = new StringReader(filterParams))
      {
          return (FilterParams)ser.Deserialize(sr);
      }
}
Run Code Online (Sandbox Code Playgroud)

请记住,您的FilterParams类必须具有默认(即无参数)构造函数,并且您可以使用该[XmlIgnore]属性来阻止属性根据需要序列化到数据库中.

public class FilterParams{
   public string Name {get;set;}
   public string Age {get;set;}

   [XmlIgnore]
   public string PropertyYouDontWantToSerialise {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

注意:SaveFilter返回Void,为简洁起见,没有错误处理.