实体框架 - "无法创建类型的常数值..."例外 [英] Entity Framework - "Unable to create a constant value of type..." exception
问题描述
有人可以帮我解决这个异常:
Can somebody help me resolve this exception:
测试方法
KravmagaTests.Model.Entities.StudentTest.Create_Valid_Student扔
异常:System.NotSupportedException:无法创建类型的常
值'Kravmaga.Models.Account。只有原始类型('如
为的Int32,String和的Guid')在这方面的支持。
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@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);
}
非常感谢。
Thanks a lot.
推荐答案
更改测试方法是这样的:
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);
包含
不在这里工作了,因为它检查是否有特定的对象实例是在 context.Accounts
集。不支持此检查到SQL翻译,只为基本类型(如除外说)。 任何
只是将过滤器表达式指定到SQL,并将其传递到数据库中。
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.
这篇关于实体框架 - "无法创建类型的常数值..."例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!