Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linq-to-sql

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 to 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)

like image 622
PeteShack Avatar asked Jul 22 '11 03:07

PeteShack


1 Answers

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))
like image 94
PeteShack Avatar answered Oct 19 '22 14:10

PeteShack