'How can I get EF to Select and only return selected columns

This is my code enter image description here

 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 });
 }

My database has more columns but I only need a select few. What am I doing wrong here.

enter image description here



Solution 1:[1]

define the model you need property as follow

public class PostModel
{
    public string Title { get; set; }
    public string Description { get; set; }
}

after you can use it in select statement

InsightsPosts = _db.InsightPosts.Where(p => p.Tags.Contains("test"))
                .Select(s => new PostModel{ Title =s.Title, Description = s.Description })

Solution 2:[2]

You can create an result model for your method.

public class FullModel
{
    public string PropertyOne { get; set; }
    public string PropertyTwo { get; set; }
}

public class ResultModel
{
    public string PropertyOne { get; set; }
}

then you can use it like this:

var results = lista.Where(p => p.PropertyOne == "one").Select(p => new ResultModel()
{
    PropertyOne = p.PropertyOne,
});

then only result model properties will exists on result

[{"PropertyOne":"one"}]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Okan Karadag
Solution 2 Henrique Urruth