Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...