不允许在查询中显式构造实体类型 [MyClass]
- 作者: 像我这样叼的有七个
- 来源: 51数据库
- 2022-12-08
问题描述
正如标题所说,我有以下例外:
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.
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
