不允许在查询中显式构造实体类型 [MyClass]

时间:2023-02-17
本文介绍了不允许在查询中显式构造实体类型 [MyClass]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所说,我有以下例外:

Like the title says, I have the following exception:

描述:事件代码:3005 事件消息:未处理的异常有发生了.异常信息:异常类型:NotSupportedException异常消息:实体类型的显式构造'公司.项目.核心.域.朋友'不允许查询.

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.

我正在使用 LINQ to SQL 并且在我的数据上下文中有以下代码:

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?

推荐答案

不能使用 LINQ 查询创建属于数据上下文的实体.这是 C# 团队经过深思熟虑的设计决策.因为实体是在 Select 语句中(手动)更新的,这意味着它们不会被 DataContext 跟踪,这可能会使开发人员感到困惑.另一方面,当 DataContext 自动在提交时插入那些新的实体,这也会令人困惑.剩下的唯一选择是与开发人员沟通这不是一个好主意,而这正是您所看到的.

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.

这篇关于不允许在查询中显式构造实体类型 [MyClass]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:不支持 Last 和 LastOrDefault 下一篇:使用 LINQ to SQL 访问系统数据库/表?

相关文章

最新文章