我有一个在ASP.NET MVC应用程序中收集数据的模型:
namespace myapp.Models
{
[Table("mytable")]
public partial class mytbl
{
// column specifications
}
}
但是该模型采用所选表的所有行。我想添加一些筛选规则。在SQL查询中,它看起来是这样的;
SELECT *
FROM mytable
WHERE mycol = 2 OR mycol = 3
在上面的例子中,我手动键入了2和3,但我有一个文本文件toshow.txt(位于wwwroot(,toshow.txt文件的内容是;
2
3
如何根据文本文件对数据进行子集设置?
我对ASP.NET MVC应用程序开发不是很熟悉。如果我的问题没有道理,我很抱歉。
提前谢谢。
您需要
- 读取文件
- 将从文件中读取的
string
s转换为int
值 - 筛选数据库中的数据
以下内容至少应该让你开始:
// get filename and read the file
string fileName = Path.Combine(_env.WebRootPath, "toshow.txt");
string[] lines = File.ReadAllLines(fileName);
// parse values in file to List<int>
List<int> filter = lines.Select(line => int.Parse(line)).ToList();
// could also be written lines.Select(int.Parse)
// filter your DB
var filteredResult = _context.MyTable.Where(x => filter.Contains(x.MyCol));
其中_env
是IWebHostingEnvironment
,WebRootPath
映射到wwwroot目录。如果使用IHostingEnvironment
,则可能需要使用ContentRootPath
。更多详细信息可以在Asp.Net Core的静态文件中找到。
以上内容将根据文件中的值筛选MyCol
。
例如,如果文件中不包含可转换为int
s的值,则还需要执行自己的错误检查和验证。