views:

39

answers:

1

Hi,

I have the following question: It is easy to insert an oBject in database with a form.

  1. Just create an object
  2. link it to the fields in your from.
  3. Post back to controller,
  4. create a new datacontext and do datacontext.InsertOnSubmit(object)

.

public static void AddPage(string lang, Page page)
                {
                    using (var db = new CardReaderDataContext())
                    {
                        page.Lang = lang;
                        page.URL = UrlHelper.CreateValidSeoUrl(page.Name, "-");
                        db.Pages.InsertOnSubmit(page);
                        db.SubmitChanges();
                    }
                }

But if you want to update an object, it is a tedious job. You do the same flow,

  1. you get the object,
  2. link it to your form,
  3. post it, but THEN !!! because it went outside your datacontext, you have to reload the object from the datacontext,
  4. transfer all the variables and save it, this is a little complex explained so I give an example:

To update an object that you modified in a form:

public static void Update(Page page)
        {
            using (var db = new CardReaderDataContext())
            {
                var _page = db.Pages.Where(p => p.Guid == page.Guid).Single();
                _page.ModificationDate = DateTime.Now;
                _page.Title = page.Title;
                _page.Description = page.Description;
                _page.Content = page.Content;
                _page.Keywords = page.Keywords;
                _page.Name = page.Name;
                _page.WTLang = page.WTLang;
                _page.WTSKU = page.WTSKU;
                _page.WTTi = page.WTTi;
                _page.WTUri = page.WTUri;
                _page.URL = UrlHelper.CreateValidSeoUrl(page.Name, "-");
                //  _page.Order = GetMaxOrderByMenuGuid(page.MenuGuid);
                db.SubmitChanges();
            }
        }

I don't know if it is clear, if it isn't comment me, I will edit

+1  A: 

I think you're looking for DataContext.Attach, but you can only use that with linqtosql objects that have been serialised/deserialised.

Have a read of the answer to this question - http://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/384a1c03-3acf-43ef-9a25-b84f93025e63/

"It's also not a good idea to even attempt to fetch the old version. By doing that you are in effect turning off optimistic concurrency, so unless you intended that this is a bad approach. What you need to do is round trip both the original state and the current state of the object."

Frank Tzanabetis
this is not really a global solution answer (I don't think there is one), but the link you provided and the ones that are present in that one are more then helpfull, and give me good insight on the question
Nealv