entity framework – “无法创建类型的常量值…”exception
有人可以帮我解决这个exception:
测试方法KravmagaTests.Model.Entities.StudentTest.Create_Valid_Student抛出exception:System.NotSupportedException:无法创建类型为“Kravmaga.Models.Account”的常量值。 在此上下文中仅支持基本类型(例如Int32,String和Guid’)。
我运行这个测试方法时得到这个:
[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); }
非常感谢。
以这种方式更改您的测试方法:
// ... 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
在这里不起作用,因为它检查特定对象实例是否在context.Accounts
设置。 不支持将此检查转换为SQL,仅适用于原始类型(如exception所述)。 Any
只是将您指定的filter表达式转换为SQL并将其传递给数据库。
entity framework正在尝试将context.Accounts.Contains(student)转换为SQL语句(例如:“WHERE … IN(…)”)。 它无法将其转换为SQL语句,因为它只知道如何处理基本类型(int,string …)因此exception。
您可能正在尝试让EF生成SQL语句,例如:
SELECT * FROM Accounts WHERE Id IN(1,2,3,4,5)
您可以编写如下LINQ To Entities语句,如下所示:
var studentIds = new int[] { 1, 2, 3, 4, 5 }; var matches = from account in context.Accounts where studentIds.Contains(account.Id) select account;
有关更多信息,请查看以下博客文章:
我提到的博客文章提供了.NET 3.5框架的解决方案。