How to include only specific properties of navigation property into the query by entity framework when lazy loading disabled?

entity-framework entity-framework-core lazy-loading

Question

LazyLoading is disabled on my project. I want to get Product which is Id = 1 with Category navigation property of it. But I need just Id and Name properties of Category. That's why I want Category navigation property to has only these two fields.Is it possible to create such a query ?

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; } 
    public dobule Price{ get; set; }
    public string Description { get; set; }
    public bool IsDeleted { get; set; }       
    public DateTime CreatedDate { get; set; }   
    public DateTime ModifiedDate { get; set; }      

    public int CategoryId{ get; set; }
    public Category Category{ get; set; }  
}

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; } 
    public dobule Description{ get; set; }
    public Category IsDeleted { get; set; }       
    public DateTime CreatedDate { get; set; }   
    public DateTime ModifiedDate { get; set; } 
}
1
0
2/3/2019 1:43:34 PM

Popular Answer

If you only want a few specific fields you will need to select them explicitly. Something like this would work:

dbContext.Products
    .Select(p => new Product
    {
        Id = p.Id,
        Name = p.Name,
        // etc... The fields you need from product go here
        Category = new Category
        {
            Id = p.Category.Id,
            Name = p.Category.Name
        }
    }

It might be better to have a Product and Category model class that only has the two fields. Now your method would return a Category object that lacks values for most fields which the caller might not expect. Depends on what exactly you're doing.

1
2/3/2019 2:01:50 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow