I have 2 models,
public class Bin : INotifyPropertyChanged
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public IList<Produit> Produits
{
get;
set;
}
}
and
public class Produit : INotifyPropertyChanged
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public bool Actif
{
get
{
return _Actif;
}
set
{
if (_Actif != value)
{
_Actif = value;
RaisePropertyChanged("Actif");
}
}
}
}
In my ViewModel I try to include Produit only if the property "Actif" is true:
Bin bins = new ObservableCollection<Bin>(await db.Bins.Include(b=>b.Produits).Where(b => b.Produits.Count() > 0).ToListAsync());
If I use:
Bin bins = new ObservableCollection<Bin>(await db.Bins.Include(b => b.Produits.Where(p => p.Actif)).Where(b => b.Produits.Count() > 0).ToListAsync());
I received an error like:
System.ArgumentException: '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.
How can I load only "Actif" products when I include "Produit" in my query?
This work perfectly:
bins = new ObservableCollection<Bin>(db.Bins.Where(b => b.Produits.Count() > 0).Select(p => new
{
p,
Produit = p.Produits.Where(pp => pp.Actif)
})
.AsEnumerable()
.Select(x => x.p)
.ToList()
);
The only problem is that it loads the entity anyway, but with a null attribute. But an IF corrects the problem.