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.
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
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.
The example from the book is storing the useraccount and version information in viewstate - which is a big hidden field that asp.net uses to maintain state and store form variables in. In fact your hidden field will probably be in viewstate if you have viewstate turned on.
If you turn viewstate off and use your hidden field then the page will probably load faster (due to the bloat involved in maintaining viewstate). But that may affect functionality.
Also the linq to sql statement in your code will generate a different outcome from the book - so I'd assume that the book code won't update as you would wish without being adapted to your needs.
@Matthew is right if you have security concerns then a plaintext hidden field is a bad place to store something (+1).
Viewstate adds a bit of encryption on the data so you it cannot be easily tampered with as opposed to doing it with raw hidden field. Best approach with user info would be to store it in session.