Home > front end >  How can I get EF to Select and only return selected columns
How can I get EF to Select and only return selected columns

Time:04-02

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

CodePudding user response:

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

CodePudding user response:

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"}]
  • Related