我有 2 个相关的 Linq to SQL 问题。请看下图,看看我的模型是什么样子的。
问题 1
我想弄清楚如何在我的 类/表上急切地加载该User.AddedByUser
字段。User
该字段是根据User.AddedByUserId
字段上的关系生成的。该表是自引用的,我试图弄清楚如何让 Linq to SQLUser.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:
以下内容也不起作用(不与上面的更新 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."
我现在真的不知道如何解决这个问题。请帮忙!
问题2
在我的数据库中的每个其他表上,因此 Linq to SQL 模型,我有两个字段,Entity.ChangedByUser
(链接到Entity.ChangedByUserId
外键/关系)和Entity.AddedByUser
(链接到Entity.AddedByUserId
外键/关系)
如何让 Linq to SQL 急切地为我加载这些字段?我需要对我的查询进行简单的连接吗?还是有其他方法?
Linq to SQL 急切加载自引用表 http://img245.imageshack.us/img245/5631/linqtosql.jpg