Maybe I’m missing something obvious, or maybe something sinister is happening, but this seems strange to me. I have a Linq to SQL data context and I’m trying to update a field on a record. The update wasn’t working, and a SQL Profiler trace showed that no update command was being issued to the database. So I narrowed down the exact lines of code and removed various variables to try to simplify.
With the where clauses unchanged, what’s going on in the debugger right now is as follows:
var foo = db.f_pp_Budgets
.Where(b => b.SeasonKey == seasonID)
.Where(b => b.Business == businessUnit)
.Where(b => b.Level == "R")
.Where(b => b.CodeKey == region.Key)
.Single().Trade;
// foo is now set to 1
db.f_pp_Budgets
.Where(b => b.SeasonKey == seasonID)
.Where(b => b.Business == businessUnit)
.Where(b => b.Level == "R")
.Where(b => b.CodeKey == region.Key)
.Single().Trade = region.Budget.Trade;
// region.Budget.Trade was (and still is) 2
// so the underlying Linq to SQL object should have a 2 in it, right?
var baz = db.f_pp_Budgets
.Where(b => b.SeasonKey == seasonID)
.Where(b => b.Business == businessUnit)
.Where(b => b.Level == "R")
.Where(b => b.CodeKey == region.Key)
.Single().Trade;
// baz is set to 1. Shouldn't it be 2?
Since the value is unchanged, calling db.SubmitChanges() naturally doesn’t send anything to the database.
Can anybody think of a reason why the value wouldn’t be changing?
Updated code: (in response to @Hogan’s answer)
var myObj = db.f_pp_Budgets
.Where(b => b.SeasonKey == seasonID)
.Where(b => b.Business == businessUnit)
.Where(b => b.Level == "R")
.Where(b => b.CodeKey == region.Key)
.Single();
var foo = myObj.Trade;
// foo is now set to 1
myObj.Trade = region.Budget.Trade;
// region.Budget.Trade was (and still is) 2
var baz = myObj.Trade;
// baz is now set to 2
The object’s value is being updated. However, db.SubmitChanges() still doesn’t send any update statements to the database.
Found the problem. It looks like the
System.Data.Linq.Table<>object was set to.IsReadOnly = truebecause the underlying table had no primary key. Makes sense, since Linq wouldn’t really have a reliable way of tracking the uniqueness of entities if no unique identifier is supplied from the database.One would hope that the generated code for the entities could make properties on the affected type without setters, or throw an exception on setting. But there may be other good reasons why that isn’t the case, of which I am unaware.