gpt4 book ai didi

c# - LINQ To SQL 忽略唯一约束异常并继续

转载 作者:太空狗 更新时间:2023-10-29 23:48:42 25 4
gpt4 key购买 nike

我在数据库中有一个名为 Users 的表

Users------ID (PK, Identity)Username (Unique Index)

I have setup a unique index on the Username table to prevent duplicates. I am then enumerating through a collection and creating a new user in the database for each item.

What I want to do is just insert a new user and ignore the exception if the unique key constraint is violated (as it's clearly a duplicate record in that case). This is to avoid having to craft where not exists kind of queries.

First off, is this going to be any more efficient or should my insert code be checking for duplicates instead? I'm drawn more to the database having that logic as this prevents any other type of client from inserting duplicate data.

My other issue is related to LINQ To SQL. I have the following code:

public class TestRepo
{
DatabaseDataContext database = new DatabaseDataContext();

public void Add(string username)
{
database.Users.InsertOnSubmit(new User() { Username = username });
}

public void Save()
{
database.SubmitChanges();
}
}

然后我遍历一个集合并插入新用户,忽略任何异常:

TestRepo repo = new TestRepo();

foreach (var name in new string[] { "Tim", "Bob", "John" })
{
try
{
repo.Add(name);
repo.Save();
}
catch { }
}

这是第一次运行,太棒了,表中有三个用户。如果我删除第二个并再次运行此代码,则不会插入任何内容。我预计第一次插入会失败并出现异常,第二次会成功(因为我刚刚从数据库中删除了该项目),第三次会失败。

似乎正在发生的事情是,一旦抛出 SqlException(即使循环继续迭代)所有下一个插入都会失败 - 即使表中没有会导致唯一违规的行。

谁能解释一下?

附言我能找到的唯一解决方法是每次在插入之前实例化 repo,然后它完全按照异常(exception)情况工作 - 表明它与 LINQ To SQL DataContext 有关。

谢谢。

最佳答案

在第二次插入时,dataContext 将再次尝试插入第一个对象,因为它位于此 dataContext 的身份映射中(您希望插入“Tim”的愿望仍在等待中 - 在第一次捕获之后)。

在第一个循环中,您要插入“Tim”在第二个“蒂姆”和“鲍勃”中在第三个“蒂姆”、“鲍勃”和“约翰”中所以你不是在第二个循环中只插入“Bob”,这就是失败的原因。

您可以尝试从缓存中的 DataContext 中删除失败的名称,但无论如何,在一个数据上下文中多次提交是非常糟糕的主意(我对此很生气)。

关于c# - LINQ To SQL 忽略唯一约束异常并继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2470704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com