LINQ to Entities contains a query

I am trying to use Contains () in a simple query, but it does not work with an error:

Cannot create a constant value of type "NewsletterApp.Models.NewsletterUser". In this context, only primitive types (such as Int32, String, and Guid) are supported.

Edit Intellisense actually directs me to use NewsletterUser in Contains () - '(NewsletterUser item)'

I read that there were problems finding an object using Contains () using EF with .NET 3.5, but I use EF4.2 (also tried 4.1) with .NET 4.0. Code below:

var db = new MyContext(); var newsletterUser = db.NewsletterUsers.Find(UserID); var subscriberList = db.Subscribers .Where(x => x.NewsletterList.ListOwner.NewsletterUsers.Contains(newsletterUser)) .ToList(); 
+4
source share
2 answers

I suspect 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 () checks for the existence of an element that satisfies the criteria specified in the lambda: "y => y.UserId == newsletterUser.UserId".

Exception you received: "Only primitive types (such as Int32, String, and Guid" are supported in this context) due to restrictions set by LINQ to Entities. LINQ to Entities must resolve your query so that it can express the database, and it cannot do this using the Contains () method with anything other than a primitive type.

The fact is that the code you published works fine if you ran it in the memory collection (LINQ to Objects) - why it is not marked by the compiler.

+7
source

Your request is incorrect. Instead of comparing a property or field, you are comparing an entire object or object that cannot be executed in this way.

Try using the following code and it will 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(); 
+1
source

Source: https://habr.com/ru/post/1392178/


All Articles