LINQ-TO-SQL Refresh()在某些外部数据库更新(如ExecuteCommand())后不更新对象的关联

假设我有一个名为Department的实体,我是从MyDataContext检索的. Department有一个名为Employees的协会.

我想在一个部门添加一堆新员工.而不是使用LINQ,这将导致多个查询,我做一个批量插入:

MyDataContext.ExcecuteCommand(
"Insert INTO Employee (DeptID,etc…),(DeptID,etc…)"
);

现在我的Department对象对这些更改一无所知,特别是Employees属性,因为Department.Employees.Count()返回0

我已经尝试了以下两种方法来刷新以更新部门及其相关的员工:

MyDataContext.Refresh(RefreshMode.OverwriteCurrentValues,Department);
MyDataContext.Refresh(RefreshMode.OverwriteCurrentValues,Department.Employees);

但仍然是Department.Employees.Count()返回0

我知道数据实际上已正确添加,因为如果我创建一个新的DataContext并获取Department实体,则Department.Employees.Count()= 3

如何在不使用新DataContext的情况下更新MyDataContext或现有的Department实体?

(我在整个请求中使用一个DataContext,并使用它执行几个不同的数据操作,因此很难尝试引入另一个DataContext)

解决方法

不幸的是,根据 this post,Refresh()不会重新加载关联.建议的解决方法是:
Department.Employees.Clear();
Department.Employees.AddRange(MyContext.Employees.Where(x=>x.DeptID=Department.DeptID))

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...