Zippy
Zippy

Reputation: 495

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

Upvotes: 0

Views: 406

Answers (2)

Henrique Urruth
Henrique Urruth

Reputation: 36

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

Upvotes: 1

Okan Karadag
Okan Karadag

Reputation: 3055

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

Upvotes: 2

Related Questions