Reputation: 3466
following is my code and relationship between the entities,
public class Expense
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ExpenseId { get; set; }
[Required]
public int CategoryId{ get; set; }
[ForeignKey("CategoryId")]
public virtual Category Category { get; set; }
public virtual List<EditedExpense> EditedExpenses { get; set; }
}
public class EditedExpense
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int EditedExpenseId { get; set; }
[Required]
public int CategoryId{ get; set; }
[ForeignKey("CategoryId")]
public virtual Category Category { get; set; }
public int ExpenseId { get; set; }
}
As you see EditedExpense is a child of Expense. Now I want to find all Expenses that their CategoryId OR the CategoryId of their EditedExpense is equal to a particular integer. Something like this:
db.Expenses.Where(exp => exp.CategoryId == 1)
.Include(exp => exp.EditedExpenses.Where(editeExp => editedExp.CategoryId == 1));
But it casts an exception and saying
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.
Parameter name: path
Am I missing something?
Upvotes: 0
Views: 56
Reputation: 3466
I solved the problem here is the code
db.Expenses.Where(exp => exp.CategoryId == 1 || exp.EditedExpenses.Any(ee => ee.CategoryId == 1).Include(exp => exp.EditedExpenses);
Upvotes: 1
Reputation: 4379
I think that you can do without the .Where in our .Include call and simply place your condition within the .Select call:
db.Expenses
.Where(exp => exp.CategoryId == 1)
.Include(exp => exp.EditedExpenses
.Select(editedExp => editeExp => editedExp.CategoryId == 1));
Upvotes: 1