c# - 在自引用表中预加载 Linq to SQL 实体

标签 c# linq-to-sql eager-loading self-reference

我有 2 个相关的 Linq to SQL 问题。请查看下图以查看我的模型的外观。

问题一

我想弄清楚如何在我的 User 类/表上预先加载 User.AddedByUser 字段。该字段是根据 User.AddedByUserId 字段上的关系生成的。该表是自引用的,我试图弄清楚如何让 Linq to SQL 急切地加载 User.AddedByUser 属性,即每当任何 User 实体是已加载/获取,它还必须获取 User.AddedByUser 和 User.ChangedByUser。但是,我知道这可能会成为一个递归问题......

更新 1.1:

我尝试按如下方式使用 DataLoadOptions:

var options = new DataLoadOptions();
options.LoadWith<User>(u => u.ChangedByUser);
options.LoadWith<User>(u => u.AddedByUser);

db = new ModelDataContext(connectionString);
db.LoadOptions = options;

但这不起作用,我在第 2 行得到以下异常:

System.InvalidOperationException occurred
  Message="Cycles not allowed in LoadOptions LoadWith type graph."
  Source="System.Data.Linq"
  StackTrace:
       at System.Data.Linq.DataLoadOptions.ValidateTypeGraphAcyclic()
       at System.Data.Linq.DataLoadOptions.Preload(MemberInfo association)
       at System.Data.Linq.DataLoadOptions.LoadWith[T](Expression`1 expression)
       at i3t.KpCosting.Service.Library.Repositories.UserRepository..ctor(String connectionString) in C:\Development\KP Costing\Trunk\Code\i3t.KpCosting.Service.Library\Repositories\UserRepository.cs:line 15
  InnerException:

异常是不言自明的——对象图不允许是循环的。 另外,假设第 2 行没有抛出异常,我很确定第 3 行会抛出异常,因为它们是重复键。

更新 1.2:

以下也不起作用(不与上面的 Update 1.1 结合使用):

var query = from u in db.Users
            select new User()
            {
                Id = u.Id,
                // other fields removed for brevityy
                AddedByUser = u.AddedByUser,
                ChangedByUser = u.ChangedByUser,

            };
return query.ToList();

它抛出以下不言自明的异常:

System.NotSupportedException occurred
Message="Explicit construction of entity type 'i3t.KpCosting.Shared.Model.User' in query is not allowed."

我现在真的不知道如何解决这个问题。请帮忙!

问题二

在我的数据库中的每个其他表上,因此在 Linq to SQL 模型上,我有两个字段,Entity.ChangedByUser(链接到 Entity.ChangedByUserId 外键/关系) 和 Entity.AddedByUser(链接到 Entity.AddedByUserId 外键/关系)

如何让 Linq to SQL 为我快速加载这些字段?我需要对我的查询进行简单的连接吗?还是有其他方法?

Linq to SQL eager loading on self referencing table http://img245.imageshack.us/img245/5631/linqtosql.jpg

最佳答案

Any type of cycles just aren't allowed .自 LoadWith<T> AssociateWith<T> 应用于上下文中的每种类型,没有内部方法来防止无限循环。更准确地说,它只是对如何创建 SQL 感到困惑,因为 SQL Server 没有 CONNECT BY 。和 CTEs确实超过了 Linq 可以使用提供的框架自动生成的内容。

您可用的最佳选择是为两个子项和匿名类型手动执行 1 级向下连接到用户表以返回它们。抱歉,这不是一个干净/简单的解决方案,但它确实是 Linq 迄今为止可用的所有解决方案。

关于c# - 在自引用表中预加载 Linq to SQL 实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1310677/

相关文章:

c#-4.0 - 类型 'X' 未映射为表

linq - 如何在 EF Core 3.1 中使用 Linq 表达式加入 Group By

linq-to-sql - 如何映射 LINQ To SQL 以启用预加载,返回 EntitySet 或 ICollection?

c# - 到 UI 的 MVVM 通知

c# - 我可以在不验证的情况下加载 XmlDocument 吗?

C# 多态错误 : is inaccessible due to its protection level

linq - 管理 LINQ to SQL .dbml 模型复杂性

c# - 在 LINQ to SQL 中,通过外键添加时是否需要 InsertOnSubmit()?

c# - 读取 CSV 文件并将值存储到数组中

ruby-on-rails - Rails 急切加载,可能的错误