Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to only load certain fields of a child object in Entity Framework 6.1?

I'm working on a model that has two classes, Product and Transaction.

public class Product
{
    [DataMember]
    public Guid ProductId {get; set;}

    [DataMember]
    public virtual ICollection<Transaction> Transactions { get; set; }
}

public class Transaction
{
    [DataMember]
    public Guid TransactionId {get; set;}

    [DataMember]
    public DateTimeOffset Date { get; set; }

    [DataMember]
    public String Customer { get; set; }
}

How do I do a query that will retrieve a product and the Date of its transactions? I tried something like

var product = db.Products.Include(p => p.Transactions.Select(t => new { t.Date })).Where(p => p.ProductId = productId);

But it throws an exception:

The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties

Edit for clarification: What I want to achieve is actually not loading TransactionId and Customer when Transaction is loaded.

like image 708
Jim Avatar asked Apr 21 '16 09:04

Jim


1 Answers

you could also try Anonymous projection

var product = db.Products.Where(p => p.ProductId = productId)
                         .Select(pr=> new 
                         {
                           product = pr,
                           transactionDates = pr.Transactions.Select(tr=>tr.Date),
                         }.ToList();
like image 102
Eldho Avatar answered Oct 14 '22 18:10

Eldho