Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including only Id of related entity in entity framework core

I am currently developing an API with ASP.NET Core and Entity framework core with npgsql as database provider. I have two Entities and they have a one to many relation. The thing is that I only want to include the Id's of the child entity in the JSON result that the "Parent Controller" returns.

These are my entities:

public class Meal {
    public int Id { get; set; }

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

    public string UserId { get; set; }
    public User User { get; set; }

    public List<Picture> Pictures { get; set; }

    public Meal () {
        this.Pictures = new List<Pictures>();
    }
}

public class Picture {
    public int Id { get; set; }

    public int MealId { get; set; }
    public Meal Meal { get; set; }

    public byte[] full { get; set; }
    public byte[] small { get; set; }
}

I am however not sure on how to achieve this. Yesterday I came across another SO question which suggested something like this:

public IActionResult Meals () {
    var meal = this.context.Meals
        .Include(m => m.Pictures.Select(p => p.Id))
        .First();

    return new JsonResult(meal);
}

This however throws an InvalidOperationException. My DbContext is very basic, no onModelConfiguring because this code is following convention for as far as I know and it just has two DbSets of the corresponding types. The foreign keys are also correct in the database and callling something like:

var pictures = dbContext.Pictures.Where(p => p.MealId == mealId).ToList();

Works as expected. I have only included the code which I thought was relevant. If more is needed I will include it, but I think this is completely my limited understanding of the queries.

Thank you for your time!

like image 995
larzz11 Avatar asked Aug 04 '16 07:08

larzz11


People also ask

How do I load related entities in Entity Framework Core?

Entity Framework Core allows you to use the navigation properties in your model to load related entities. There are three common O/RM patterns used to load related data. Eager loading means that the related data is loaded from the database as part of the initial query.

How do I get identity value in EF core?

EF execute each INSERT command followed by SELECT scope_identity() statement. SCOPE_IDENTITY returns the last identity value inserted into an identity column in the same scope. The above example will execute the following SQL in the database. WHERE @@ROWCOUNT = 1 AND [StudentID] = scope_identity();

What difference does AsNoTracking () make?

AsNoTracking(IQueryable)Returns a new query where the entities returned will not be cached in the DbContext or ObjectContext. This method works by calling the AsNoTracking method of the underlying query object.

What is include in Entityframework?

Entity Framework Classic Include The Include method lets you add related entities to the query result. In EF Classic, the Include method no longer returns an IQueryable but instead an IncludeDbQuery that allows you to chain multiple related objects to the query result by using the AlsoInclude and ThenInclude methods.


1 Answers

You don't need to change your DB structure, one option is like so:

        var db = this.context;
        var result = (from meal in db.Meals
                      where meal.<whatever> == "123"
                      select new
                      {
                         Id = meal.Id,
                         Title = meal.Title,
                         Description = meal.Description,
                         //other required meal properties here.
                         PictureIds = meal.Pictures.Select(x => x.Id)
                      }).ToList();

You can do the same thing via lambda as well by using the "Select" method, Linq in such things seem more intuitive to me, however, to each his own... that's your choice.

like image 85
Sumit Maingi Avatar answered Nov 15 '22 09:11

Sumit Maingi