Query is included in LINQ to Entities.

entity-framework

Question

When I attempt to use Contains() in a straightforward query, it fails with the following error:

Constants of the 'NewsletterApp.Models.NewsletterUser' type could not be created. In this situation, only primitive types (such Int32, String, and Guid) are supported.

Using the NewsletterUser in Contains() -'(NewsletterUser item)' is what the intellisense truly advises me to do.

I've heard that using Contains() with EF and.NET 3.5 may cause problems, however I'm using EF4.2 (I've also tested 4.1) and.NET 4.0 without any problems. Here is the code:

        var db = new MyContext(); 

        var newsletterUser = db.NewsletterUsers.Find(UserID);
        var subscriberList = db.Subscribers
              .Where(x => x.NewsletterList.ListOwner.NewsletterUsers.Contains(newsletterUser))
              .ToList();
1
4
1/21/2012 11:31:32 AM

Accepted Answer

I believe you want this.

var db = new MyContext(); 
var newsletterUser = db.NewsletterUsers.Find(UserID);
var subscriberList = db.Subscribers
          .Where(x => x.NewsletterList.ListOwner.NewsletterUsers
                     .Any(y => y.UserId == newsletterUser.UserId))
          .ToList();

Any() verifies if an item exists that meets the requirements stated in the lambda: "y => y.UserId == newsletterUser.UserId."

The constraint imposed by LINQ to Entities is the cause of the problem you were receiving: "Only primitive types ('such as Int32, String, and Guid' are supported in this context." Since anything other than a primitive type may be sent to the Contains() function, LINQ to Entities cannot resolve your query in a form that it can express to the database.

The code you supplied works quite fine when executed against an in-memory collection (LINQ to Objects), which is why the compiler didn't detect it.

7
1/21/2012 8:31:02 AM

Popular Answer

Your question is flawed. You are comparing the whole object or entity rather than just a particular property or field, which is impossible to accomplish in this way.

The following code should work.

var db = new MyContext(); 
var newsletterUser = db.NewsletterUsers.Find(UserID);
var subscriberList = db.Subscribers
          .Where(x => x.NewsletterList.ListOwner.NewsletterUsers.UserId.Contains(newsletterUser.UserID))
          .ToList();


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow