Код: Выделить всё
System.ArgumentException: 'Instance property 'Name' is not defined for type 'System.Collections.Generic.ICollection`1[Child]' (Parameter 'propertyName')'
Код: Выделить всё
public class Parent
{
public int Id { get; set; }
public string Name { get; set; }
public Child Child { get; set; } // Its worked
public ICollection Children { get; set; } // This collection does not work.
}
// Sample child entity
public class Child
{
public int Id { get; set; }
public string Name { get; set; }
public int ParentId { get; set; }
public Parent Parent { get; set; }
}
Код: Выделить всё
public static void Main()
{
using (var context = new MyDbContext())
{
// Example of filtering by parent entity and its collection of child entities.
var filters = new Dictionary
{
{ "Name", "Parent1" },
{ "Child.Name","Child2" } //Worked
{ "Children.Name", "Child1" } // Not work
};
var results = ApplyDynamicWhereClause
(context.Parents, filters).Include(p => p.Children).ToList();
foreach (var parent in results)
{
Console.WriteLine($"{parent.Name}:");
foreach (var child in parent.Children)
{
Console.WriteLine($" {child.Name}");
}
}
}
public IQueryable ApplyDynamicWhereClause(IQueryable query, Dictionary filters)
{
var parameter = Expression.Parameter(typeof(T), "x");
Expression predicate = Expression.Constant(true);
foreach (var filter in filters)
{
string[] propertyPath = filter.Key.Split('.');
Expression property = parameter;
Type currentType = typeof(T);
foreach (var propertyName in propertyPath)
{
property = Expression.Property(property, propertyName);
currentType = currentType.GetProperty(propertyName).PropertyType;
}
var constant = Expression.Constant(filter.Value);
var equals = Expression.Equal(property, constant);
predicate = Expression.AndAlso(predicate, equals);
}
var lambda = Expression.Lambda(predicate, parameter);
return query.Where(lambda);
}
}
Код: Выделить всё
public class MyDbContext : DbContext
{
public DbSet Parents { get; set; }
public DbSet Children { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//optionsBuilder.UseInMemoryDatabase("TestDb");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Seed some data for testing
modelBuilder.Entity().HasData(
new Parent { Id = 1, Name = "Parent1" },
new Parent { Id = 2, Name = "Parent2" });
modelBuilder.Entity().HasData(
new Child { Id = 1, Name = "Child1", ParentId = 1 },
new Child { Id = 2, Name = "Child2", ParentId = 1 },
new Child { Id = 3, Name = "Child3", ParentId = 2 });
}
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... d-but-does