Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Can somebody help me resolve this exception:

Test method KravmagaTests.Model.Entities.StudentTest.Create_Valid_Student threw exception: System.NotSupportedException: Unable to 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 test method:

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

Thanks a lot.

like image 418
Iškuda Avatar asked Sep 11 '11 15:09

Iškuda


1 Answers

Change your test method this way:

// ...
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 doesn't work here because it checks if a particular object instance is in the context.Accounts set. Translation of this check into SQL is not supported, only for primitive types (like the exception says). Any just translates the filter expression you specify into SQL and passes it to the database.

like image 179
Slauma Avatar answered Nov 02 '22 15:11

Slauma