none
DBContext - Get entities based on a list RRS feed

  • Question

  • I'm trying to implement a function that searches for entities based on a list.

    My code:

        public IQueryable<TEntity> GetQuery<TEntity>() where TEntity : class
        {
         var entityName = GeTEntityName<TEntity>();
         return ((IObjectContextAdapter)DbContext).ObjectContext.CreateQuery<TEntity>(entityName);
        }
        
        public void GetCustomers(IList<Customer> searchList)
        {
         var customerList = this.GetQuery<Customer>().Any(c => searchList.Any(l => l.ID == c.ID)).ToList();
        }

    When executing the GetCustomers function i get an exception:

    Unable to create a constant value of type 'Customer'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.

    What is wrong?

    Wednesday, December 4, 2013 8:18 PM

Answers

  • Hi. As the error message says Linq to Entities only supports contains/any queries against primitive types. You will need to extract the IDs from searchList into an IEnumerable<int> and then use that in the query.

    public void GetCustomers(IList<Customer> searchList)
    {
        List<int> Ids = searchList.Select(o => o.Id).ToList();
        var customerList = this.GetQuery<Customer>().Any(c => Ids.Contains(c.ID)).ToList();
    }

    • Marked as answer by Syslock Thursday, December 5, 2013 8:46 AM
    Thursday, December 5, 2013 12:26 AM

All replies

  • Try

     public void GetCustomers(IList<Customer> searchList)
        {
         var customerList = this.GetQuery<Customer>().Where(c => searchList.Contains(c.ID)).ToList();
        }

    David


    David http://blogs.msdn.com/b/dbrowne/

    Wednesday, December 4, 2013 9:22 PM
  • Hi. As the error message says Linq to Entities only supports contains/any queries against primitive types. You will need to extract the IDs from searchList into an IEnumerable<int> and then use that in the query.

    public void GetCustomers(IList<Customer> searchList)
    {
        List<int> Ids = searchList.Select(o => o.Id).ToList();
        var customerList = this.GetQuery<Customer>().Any(c => Ids.Contains(c.ID)).ToList();
    }

    • Marked as answer by Syslock Thursday, December 5, 2013 8:46 AM
    Thursday, December 5, 2013 12:26 AM