我有一个查询,它返回一个包含4列的表:
ItemName |国家A |国家B |国家C |
我的应用中有一些授权流程,有些用户只能看到特定的国家/地区列。
例如,声明country = A的用户应该只看到:
ItemName |国家A |
有没有办法根据列的名称过滤列?
IQueryable<AllCountries> ResultsVM = _context.AllCountries;
var country = IdentityExtensions.GetCountryId(User);
if (country != null)
{
Type elementType = ResultsVM.ElementType;
foreach (PropertyInfo pi in elementType.GetProperties())
{
if (country==pi.Name)
{
ResultsVM= _context.AllCountries
.Select(t => new AllCountries
{
ItemName=t.ItemName,
?? only the column which matches the country
});
}
}
}
到目前为止,我知道我的IQueryable列与用户所在的国家/地区相对应,但我不知道如何在我的选择中显示并删除其他人...
更新
我的ViewModel ResultsVM存储IQueryable并将在我的MVC web项目的View中使用,定义为以下列表:
public class AllCountries
{
[DisplayName("Item")]
public string ItemName { get; set; }
public int? Country1 { get; set; }
public int? Country2 { get; set; }
public int? Country3 { get; set; }
}
谢谢
西尔
答案 0 :(得分:0)
考虑Columns的名称前缀是Country,并且您要选择该列的条件是Ex的该列的后缀:
Country + '1'
Country + '2'
Country + '3'
Country + '4'
然后,您可以在LINQ查询中创建动态选择,如下所示:
public class Country
{
public string Condition { get; set; }
public string Country1 { get; set; }
public string Country2 { get; set; }
public string Country3 { get; set; }
}
public void GetData()
{
List<Country> liCountry = new List<Country>();
liCountry.Add(new Country { Condition = "1", Country1 = "2", Country2 = "3", Country3 = "4" });
liCountry.Add(new Country { Condition = "2", Country1 = "20", Country2 = "30", Country3 = "40" });
liCountry.Add(new Country { Condition = "3", Country1 = "21", Country2 = "31", Country3 = "41" });
string temp = "2";
var liResult = liCountry.Where(w => w.Condition == temp).Select(s => new {result = s.GetType().GetProperty("Country" + temp).GetValue(s, null) }).ToList();
}
在select语句中,我使用Reflection
动态获取列名。