Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit construction of entity type [MyClass] in query is not allowed

Like the title says, I have the following exception:

Description: Event code: 3005 Event message: An unhandled exception has occurred. Exception information: Exception type: NotSupportedException Exception message: Explicit construction of entity type 'Company.Project.Core.Domain.Friend' in query is not allowed.

I am using LINQ to SQL and have the following code in my datacontext:

var friends2 = (
    from f in dc.Friends
    where f.MyFriendsAccountId == accountId
    where f.AccountId != accountId
    select new 
    {
        f.FriendId,
        AccountId = f.MyFriendsAccountId,
        MyFriendsAccountId = f.AccountId, 
        f.CreateDate,
        f.Timestamp
    }).Distinct();

result.AddRange(
    from o in friends2
    select new Friend()
    {
        FriendId = o.FriendId, 
        AccountId = o.AccountId, 
        CreateDate = o.CreateDate, 
        MyFriendsAccountId = o.MyFriendsAccountId, 
        Timestamp = o.Timestamp
    });

the final code block is throwing the error and I am pretty sure it is this statement that is the culprit:

.Select( o => **new Friend**

How should I be reworking my code to avoid this error?

like image 841
Peter Avatar asked Jun 01 '10 19:06

Peter


2 Answers

Entities that are part of the data context can not be created using a LINQ query. This is a well thought design decision of the C# team. Because the entities are newed up (manually) in the Select statement, this would mean that they are not tracked by the DataContext and this can confuse developers. On the other hand, when the DataContext would automatically insert on submit those newed up entities, this would be confusing as well. The only option left was communicating to the developers that this is not such a good idea to do, and that is what you saw happening.

like image 188
Steven Avatar answered Nov 09 '22 22:11

Steven


It will work if you don't have PrimaryKey set on any columns in your Friends class. That way changes won't be tracked for that class anymore, but your code will work.

like image 37
Vedran Avatar answered Nov 09 '22 22:11

Vedran