How did I wrong my DataContext?

你。 提交于 2019-12-10 16:38:47

问题


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 :

  1. Remove the objects that were erroneous.
  2. Close Visual Studio.
  3. Reopen Visual Studio.
  4. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!