开发者

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

开发者 https://www.devze.com 2023-03-27 05:47 出处:网络
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 instea

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?


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


//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"


    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消