views:

1617

answers:

3

I'm using LINQ to SQL and C#. I have two LINQ classes: User and Network.

User has UserID (primary key) and NetworkID

Network has NetworkID (primary key) and an AdminID (a UserID)

The following code works fine:

user.Network.AdminID = 0;
db.SubmitChanges();

However, if I access the AdminID before making the change, the change never happens to the DB. So the following doesn't work:

if(user.Network.AdminID == user.UserID)
{
     user.Network.AdminID = 0;
     db.SubmitChanges();
}

It is making it into the if statement and calling submit changes. For some reason, the changes to AdminID never make it to the DB. No error thrown, the change just never 'takes'.

Any idea what could be causing this?

Thanks.

+2  A: 

I just ran a quick test and it works fine for me.

I hate to ask this, but are you sure the if statement ever returns true? It could be you're just not hitting the code which changes the value.

Other than that we might need more info. What are the properties of that member? Have you traced into the set statement to ensure the value is getting set before calling SubmitChanges? Does the Linq entity have the new value after SubmitChanges? Or do both the database AND the Linq entity fail to take the new value?

In short, that code should work... so something else somewhere is probably wrong.

Telos
A: 

Here's the original post.


Here's a setter generated by the LinqToSql designer.

Code Snippet

{
  Contact previousValue = this._Contact.Entity;
  if (((previousValue != value)
    || (this._Contact.HasLoadedOrAssignedValue == false)))
  {
    this.SendPropertyChanging();
    if ((previousValue != null))
    {
      this._Contact.Entity = null;
      previousValue.ContactEvents.Remove(this);
    }
    this._Contact.Entity = value;
    if ((value != null))
    {
      value.ContactEvents.Add(this);
      this._ContactID = value.ID;
    }
    else
    {
      this._ContactID = default(int);
    }
    this.SendPropertyChanged("Contact");
  }
}

This line sets the child's property to the parent.

this._Contact.Entity = value;

This line adds the child to the parent's collection

value.ContactEvents.Add(this);

The setter for the ID does not have this second line.

So, with the autogenerated entities... This code produces an unexpected behavior:

myContactEvent.ContactID = myContact.ID;

This code is good:

myContactEvent.Contact = myContact;

This code is also good:

myContact.ContactEvents.Add(myContactEvent);
David B
A: 

I had this issue. The reason was one dumb line of code:

DBDataContext db { get { return new DBDataContext(); } }

obviously it should be:

DBDataContext db = new DBDataContext();
Alex Kazanskiy