Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update Record Linq-to-SQL

I am reading a book - ASP.Net 3.5 Enterprise Application Development with Visual Studio 2008 and when it talks about updating a record in the database using Linq-to-SQL it uses this code:

MyUserAccount ua = new MyUserAccount
{
... Update fields
};

ua.UserAccountID = Convert.ToInt32(session["UserAccountID"]);
ua.Version = Convert.ToInt32(session["Version"]);

MyDataContext db = new MyDataContext();
db.MyUserAccounts.Attach(ua,true);
db.SubmitChanges();

Versus what I am used to, where I just save the AccountID in a session variable and then get the record from the database, make my changes, and then submit the changes.

BtnUpdate

int UserAccountID = Convert.ToInt32(Request["UserAccountID"]);

//Get User fron Context
MyDataContext db = new MyDataContext();
MyUserAccount ua = db.MyUserAccounts.Single(
     x => x.UserAccountID == UserAccountID);

//Make changes
ua.Blah = "";

db.SubmitChanges();

So my question is what is the preferred way to do this? Having not seen this in the past I am not sure what the preferred or best way is. Any help is appreciated.

Wade

Note:

My original question, someone changed my title, was what was the best Linq-to-SQL way to update the record. So I changed the code to use session variables and the title back to it's original. Please, read the whole question as I am only looking for the best method to update my record in the database using Linq-to-SQL.

like image 647
Wade73 Avatar asked Mar 21 '26 11:03

Wade73


2 Answers

In terms of sql produced the former will generate a Sql statement something like

Update MyUserAccount set blah=@Blah where UserAccountID = @UserAccountID

whereas the latter will produce

Select UserAccountID, Blah, ....  From MyUserAccount where UserAccountID = @UserAccountID
Update MyUserAccount set blah=@Blah where UserAccountID = @UserAccountID
like image 199
sgmoore Avatar answered Mar 24 '26 01:03

sgmoore


Do neither, store critical data like that into the session. Hidden fields (viewstate is a hidden field) are possible to be tampered by the user. Session will prevent the user from being able to change the value.

like image 29
Matthew Avatar answered Mar 24 '26 01:03

Matthew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!