问题
I've been working with LINQ To SQL for some time now, and what I usually do in a solution is the following:
- In a project I create a dbml schema.
- In another project I create a simple DataAccessLayer (DAL) that knows my first project, and instantiates a DataContext.
- In the 3rd project (Business logic) I instantiate my DAL.
This usually works well. However, this time, I don't know why, but "It" doesn't work. "It" being "Me updating the database". I changed my code around to do some tests, and I get a result I don't understand.
MyDataContext dataContext = new MyDataContext(MyConnectionString);
DataBaseItem dbi = (from item in dataContext.DataBaseItems
where item.ID == 1
select item).First();
dbi.Name= "toto";
// dataContext.GetChangeSet() tells me nothing changed.
I dug deeper by breaking into the bdi.Name = "toto";
and compared it with a similar value assignment in a project where it works (both are designer generated code) and saw that some code was missing (I wrote them down there, but I commented them so you see what is missing) :
[Column(Storage="_Name", DbType="NVarChar(250)")]
public string Name
{
get
{
return this._Name;
}
set
{
if ((this._Name!= value))
{
//this.OnLayoutChanging(value);
//this.SendPropertyChanging();
this._Name= value;
//this.SendPropertyChanged("Name");
//this.OnLayoutChanged();
}
}
}
Anyone can tell me how come these lines are missing, and where did I messed up?
When I do dataContext.Refresh(RefreshMode.KeepChanges, dataContext.DataBaseItems);
, I get an error:
An object specified for refresh is not recognized.
回答1:
If your objects do not have a primary key, then the objects will not be tracked for changes. It is probable ID was not set as primary key in the dbml.
回答2:
The error was within the IDE (VS2008). The generation, or regeneration, of any Linq-to-Sql object by the IDE was faulty. To fix the problem, I had to :
- Remove the objects that were erroneous.
- Close Visual Studio.
- Reopen Visual Studio.
- Recreate the objects.
Not doing the first stop and instead have the object regenerated by changing a parameter could have worked, but I can't test it, since I don't know how to reproduce the problem.
来源:https://stackoverflow.com/questions/4187167/how-did-i-wrong-my-datacontext