xplat
xplat

Reputation: 8636

Can I update 1 object only with Linq to SQL?

Its a simple question, but I'm not aware of the answer and I couldn't get it to work.

Can I update only one entity on the entire DataContext? Or should I follow plain ADO.NET for this operation only?

Edit:

public MyObject GetMyObjectById(int selectedId)
    {
        DataContext db = _dbManager.GetContext();

        return db.MyObject.SingleOrDefault(p => p.Id == selectedId);
    }

I am getting an object with the above query... I am querying then for an integer...on another table/object

 public int GetMyInteger()
    {
        DataContext db = _dbManager.GetContext();

        return db.MyAnotherObject.FirstOrDefault().MyInteger;
    }

Everything is fine for all my operations...but now i just want to update only the integer i got from the database...

 public void SetMyInteger(int updInteger)
    {
        DataContext db = new DataContext(ConnectionString);

        MyAnotherObject theEntity = db.MyAnotherObject.FirstOrDefault();
        atheEntity.MyInteger = updInteger;
        db.SubmitChanges(ConflictMode.ContinueOnConflict);
    }

The above method deleted MyObject i got from the first query!!! Of course if i use the static context DataContext tries to update MyObject and MyAnotherObject which seems the correct behaviour.

Edit:

I have changed the method getting the integer with a new datacontext as well and seems to working correctly, i have a strange thought on why called the delete method, because it was the method that was called, but again .. is working now...

Thank you all for your time.

Upvotes: 4

Views: 202

Answers (2)

Mark Byers
Mark Byers

Reputation: 839114

Yes, you can:

Foo foo = dc.Foos.Where(foo => foo.Id == 345).Single();
foo.Name = "foo";
dc.SubmitChanges();

Upvotes: 1

Ahmad Mageed
Ahmad Mageed

Reputation: 96557

Yes it's possible. What have you tried? It should be as simple as this:

using (var dc = new YourDataContext())
{
    Person p = dc.Persons.Take(1).Single();
    p.FirstName = "Ahmad";
    dc.SubmitChanges();
}

Upvotes: 3

Related Questions