简体   繁体   English

实体框架-过滤子实体

[英]Entity Framework - filter child entity

I used entity framework with my example. 我在示例中使用了实体框架。 I wanted to filter child entity but it break program at run time with error: "The entity or complex type 'CodeFirstNamespace.Customer' cannot be constructed in a LINQ to Entities query." 我想过滤子实体,但它会在运行时中断程序,并显示错误:“无法在LINQ to Entities查询中构造实体或复杂类型'CodeFirstNamespace.Customer'。” Can anyone help me? 谁能帮我? Thanks. 谢谢。

public class Customer
    {
        public int CustomerID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        //public virtual ICollection<Address> Addresses
        public List<User> Users { get; set; }
        public List<Address> Addresses { get; set; }
        public List<Order> Orders { get; set; }
        public List<CheckProduct> CheckProducts { get; set; }
    }

public Customer GetCustomerCheckProduct(string email, Byte checkType)
    {
        IQueryable<Customer> customers = context.Set<Customer>().Include("CheckProducts").Where(c => c.Email == email);
        if (checkType != 0)
        {
            var cus = customers.Select(customer => new Customer { CheckProducts = customer.CheckProducts.Where(s => s.CheckType == checkType).ToList() }).SingleOrDefault();
            return cus;
        }

        return null;
    }

假设您要查找具有给定类型的CheckProducts的第一个(如果有的话)客户,为什么不简单地使用它呢?

var cus = customers.FirstOrDefault(c => c.CheckProducts.Any(cp => cp.Checktype == checkType));

To filter a collection navigation property you can do the following: 要过滤集合导航属性,您可以执行以下操作:

var customer = <get customer entity>;

var filteredCheckProducts = context.Entry( customer )
    .Collection( c => c.CheckProducts )
    .Query()
    .Where( cp => cp.CheckType == checkType )
    .ToArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM