Will
Will

Reputation: 10421

linq-to-sql inserting unique row that already exists?

If you insert a row that already exists with a unique column, what happens? Does it silently fail or does it update the record? If it updates the row that exists, is there a way to have it fail instead? Or am I stuck using select to check for the row first?

Upvotes: 0

Views: 1109

Answers (2)

The Internet
The Internet

Reputation: 8103

//EDIT: I updated the code to fit what you're looking for. In SQL Server please ensure that your Table Primary Key Column is an identity column with both seed and increment set to 1. When you try to submit your class DON'T ADD the primary key. It will use this automagically.

An exception will be thrown if you attempt to insert a row into a table with the same unique ID. Updates in Linq-To-Sql are tricky... See my code below. The first part will fail but will be caught inside the try-catch. The second part is how to do an update. You gotta pull it out based on the primary key, change the fields, then submit it. See this blog: http://www.richardbushnell.net/2008/02/18/how-to-update-data-with-linq-to-sql/

class Program
{
    static void Main(string[] args)
    {
         DataClasses1DataContext ctx = new DataClasses1DataContext();
        try
        {
            for (int i = 0; i < 10; i++)
            {

                ctx.Table_1s.InsertOnSubmit(new Table_1
                {
                    Name = "John"
                });
                ctx.SubmitChanges(System.Data.Linq.ConflictMode.FailOnFirstConflict);
            }

            var list = from i in ctx.Table_1s
                       select i;

            foreach (var item in list)
            {
                Console.WriteLine(item.Name);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        //OUTPUT: "John"
        //        "John"
        //        "John" 
        //        "John"
        //        "John"
        //        "John"
        //        "John"
        //        "John"
        //        "John"
        //        "John"
        //        "John"


    }
}

Upvotes: 2

Bob Vale
Bob Vale

Reputation: 18474

You will get an exception generated by the backend sql server.

Upvotes: 2

Related Questions