0

I have a table called Code in my LINQ to SQL datacontext. I also have a class called Codes in my Models folder. What I want to do is save the updated object Codes to my database table Code. Is this possible?

In my controller, I would pass the edited Object to my Model. My CodesRepository file contains this:

public Codes EditCode(Codes CodeToEdit)
        {
            private EventsDataContext _db = new EventsDataContext();
            Codes C = new Codes();
            C = CodeToEdit;

            _db.Codes.InsertOnSubmit(C); //error here, something about invalid arguments
             //InsertOnSubmit is for adding a new object, but I don't know the syntax
             // for editing an existing object.  

            _db.SubmitChanges();


        }

This is probably not the correct way of doing this so can someone point me in the right direction? Do I even need a class called Codes or do I need to somehow just use my database table? Thanks.


Solution: I decided to change from Linq to SQL to an Entity Framework and it works much better. This way, I don't have to define my Codes class since it comes straight from the database and I was able to delete the Codes class file.

1 Answer 1

1

You should use DataContext.Attach when you get an object back that corresponds to en existing row in the database. For Linq-to-sql's optimistic concurrency handling to work this requires that you either have the original, unsaved object available, or that you have a TimeStamp column in the database. The latter is preferred, as it only requires one extra field to be handled (probably through a hidden field in the web form).

Sign up to request clarification or add additional context in comments.

3 Comments

+1 for answering Linq To SQL and not Entity Framework! Cheers
I tried this: _db.Codes.Attach(CodeToEdit); but i still get an error. I don't think I can take an instance of my object Codes and save it to my Code database table.
There is some more info at msdn.microsoft.com/en-us/library/bb546187.aspx, which describes how to handle the attaching and optimistic concurrency.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.