Entity Framework - exception "Unable to create constant value of type ..."

Can someone help me resolve this exception:

The test method KravmagaTests.Model.Entities.StudentTest.Create_Valid_Student threw an exception: System.NotSupportedException: cannot create a constant value of type "Kravmaga.Models.Account". Only primitive types ("such as Int32, String, and Guid ') are supported in this context.

I get this when I run this testing method:

[TestMethod] public void Create_Valid_Student() { Student student = new Student() { Username = "username", Firstname = "firstname", Surname = "surname", Email = " email@gmail.com ", Password = "password", }; KravmagaContext context = new KravmagaContext(); context.AddToAccounts(student); context.Save(); bool exists = context.Accounts.Contains(student); // THIS THROWS EXCEPTION Assert.IsTrue(exists); } 

Many thanks.

+6
source share
2 answers

Change your testing method as follows:

 // ... context.Save(); int newStudentId = student.Id; // because the Id generated by the DB is available after SaveChanges bool exists = context.Accounts.Any(a => a.Id == newStudentId); Assert.IsTrue(exists); 

Contains does not work here because it checks to see if a particular instance of the object is in the set context.Accounts . Translation of this check into SQL is not supported, only for primitive types (for example, this indicates an exception). Any simply translates the specified filter expression into SQL and passes it to the database.

+9
source

Entity Framework tries to translate context.Accounts.Contains (student) into an SQL statement (for example: "WHERE ... IN (...)"). He cannot translate it into an SQL statement, since he only knows how to handle primitive types (int, string ...), hence the exception.

You are probably trying to create an EF SQL statement, for example:

SELECT * FROM Accounts WHERE Id IN (1, 2, 3, 4, 5)

You can write a LINQ To Entities statement like this:

  var studentIds = new int[] { 1, 2, 3, 4, 5 }; var matches = from account in context.Accounts where studentIds.Contains(account.Id) select account; 

For more information, see the following blog post:

http://blogs.msdn.com/b/alexj/archive/2009/03/26/tip-8-writing-where-in-style-queries-using-linq-to-entities.aspx

The blog post I mentioned offers a job for the .NET 3.5 platform.

0
source

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


All Articles