开发者

LINQ-TO-SQL Refresh() not updating object's associations after some external database update such as ExecuteCommand()

开发者 https://www.devze.com 2023-03-22 07:37 出处:网络
Lets say I have an entity called Department that I retrieved from MyDataContext.Department has an association called Employees.

Lets say I have an entity called Department that I retrieved from MyDataContext. Department has an association called Employees.

I want to add a bunch of new Employees to a Department. Instead of using LINQ, which would result in multiple queries, I do one bulk insert with:

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

Now my Department object doesn’t know anything about those changes, specifically the Employees property, because Department.Employees.Count() returns 0

I've tried both of the following t开发者_开发问答o do a Refresh to update the Department and it's related Employees:

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

But still Department.Employees.Count() returns 0

I know the data was actually added correctly, because if I create a new DataContext and get the Department entity, Department.Employees.Count() = 3

How can I update MyDataContext, or my existing Department entity without using a new DataContext?

(I use one DataContext throughout the entire request, and perform several different data manipulations with it, so it would be difficult to try to introduce another DataContext)


Unfortunately, according to this post, Refresh() will not reload associations. The suggested workaround is:

Department.Employees.Clear();
Department.Employees.AddRange(MyContext.Employees.Where(x=>x.DeptID=Department.DeptID))
0

精彩评论

暂无评论...
验证码 换一张
取 消