我怎样才能让 EF 到 Select 并且只有 return 选定的列
How can I get EF to Select and only return selected columns
这是我的代码
public IEnumerable<InsightPost> InsightsPosts { get; set; }
public void OnGet()
{
InsightsPosts = _db.InsightPosts.Where(p => p.Tags.Contains("test")).SelectMany(s => new { s.Title, s.Description });
}
我的数据库有更多的列,但我只需要 select 几个。我在这里做错了什么。
定义您需要的模型属性如下
public class PostModel
{
public string Title { get; set; }
public string Description { get; set; }
}
在你可以在select语句中使用它之后
InsightsPosts = _db.InsightPosts.Where(p => p.Tags.Contains("test"))
.Select(s => new PostModel{ Title =s.Title, Description = s.Description })
您可以为您的方法创建一个结果模型。
public class FullModel
{
public string PropertyOne { get; set; }
public string PropertyTwo { get; set; }
}
public class ResultModel
{
public string PropertyOne { get; set; }
}
那么你可以这样使用它:
var results = lista.Where(p => p.PropertyOne == "one").Select(p => new ResultModel()
{
PropertyOne = p.PropertyOne,
});
那么只有结果模型属性会存在于结果
[{"PropertyOne":"one"}]
这是我的代码
public IEnumerable<InsightPost> InsightsPosts { get; set; }
public void OnGet()
{
InsightsPosts = _db.InsightPosts.Where(p => p.Tags.Contains("test")).SelectMany(s => new { s.Title, s.Description });
}
我的数据库有更多的列,但我只需要 select 几个。我在这里做错了什么。
定义您需要的模型属性如下
public class PostModel
{
public string Title { get; set; }
public string Description { get; set; }
}
在你可以在select语句中使用它之后
InsightsPosts = _db.InsightPosts.Where(p => p.Tags.Contains("test"))
.Select(s => new PostModel{ Title =s.Title, Description = s.Description })
您可以为您的方法创建一个结果模型。
public class FullModel
{
public string PropertyOne { get; set; }
public string PropertyTwo { get; set; }
}
public class ResultModel
{
public string PropertyOne { get; set; }
}
那么你可以这样使用它:
var results = lista.Where(p => p.PropertyOne == "one").Select(p => new ResultModel()
{
PropertyOne = p.PropertyOne,
});
那么只有结果模型属性会存在于结果
[{"PropertyOne":"one"}]