Can I update 1 object only with Linq to SQL?

This is a simple question, but I do not know the answer, and I could not get it to work.

Can I update only one object in the entire DataContext? Or should I follow a simple ADO.NET just for this operation?

Edit:

public MyObject GetMyObjectById(int selectedId) { DataContext db = _dbManager.GetContext(); return db.MyObject.SingleOrDefault(p => p.Id == selectedId); } 

I get an object with the above query ... Then I request 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 retrieved 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 removed MyObject, which I received from the first request !!! Of course, if I use a static context, the DataContext tries to update MyObject and MyAnotherObject, which seems correct.

Edit:

I changed the method, getting an integer with the new datacontext, and it seems to work correctly, I have a strange thought about why the delete method is called, because it was a method that was called, but again .. it works now ...

Thank you all for your time.

+4
source share
2 answers

Yes it is possible. What have you tried? It should be so simple:

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

Yes, you can:

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

Source: https://habr.com/ru/post/1303071/


All Articles