Entity Framework - “Unable to create a constant value of type…” exception

后端 未结 2 1797
执念已碎
执念已碎 2020-12-06 19:09

Can somebody help me resolve this exception:

Test method KravmagaTests.Model.Entities.StudentTest.Create_Valid_Student threw exception: System

2条回答
  •  感情败类
    2020-12-06 19:53

    The Entity Framework is trying to translate the context.Accounts.Contains(student) into an SQL statement (e.g.: "WHERE ... IN (...)"). It cannot translate it into an SQL statement because it only knows how to handle primitive types (int, string...) hence the exception.

    You are probably trying to have the EF generate an SQL statement such as:

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

    You can write such a LINQ To Entities statement as follows:

     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 take a look at 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 work around for the .NET 3.5 framework.

提交回复
热议问题