我正在尝试使用LINQ将数据加载到SQL中。当我到达context.SubmitChanges()
时,抛出以下异常:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.Linq.dll
Additional information: Violation of UNIQUE KEY constraint 'UQ__SDA_Cont__403B95D755FFB06A'. Cannot insert duplicate key in object 'dbo.SDA_Contracts'. The duplicate key value is (3M).
以下是产生错误的代码。我手动进入数据(通过在调试器中查找订单并查看它)。如异常所示,没有重复的条目。
var noDuplicates = query
.GroupBy(x => x.ContractingParty)
.Select(x => x.First());
var duplicates = query
.Select(x => { x.ContractingParty = x.ContractingParty + "-2"; return x; })
.GroupBy(x => x.ContractingParty)
.Where(g => g.Count() > 1)
.Select(x => x.Skip(1).Take(1).Single());
Console.WriteLine(query.Count() + " Total entries");
Console.WriteLine(noDuplicates.Count() + " Unique entries based on contracting party");
Console.WriteLine(duplicates.Count() + " Non-unique entries");
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (DataContext context = new DataContext(conn))
{
Table<Contract> contracts = context.GetTable<Contract>();
Table<Attachment> attachments = context.GetTable<Attachment>();
contracts.InsertAllOnSubmit(noDuplicates);
contracts.InsertAllOnSubmit(duplicates);
context.SubmitChanges();
Console.WriteLine("Contracts inserted");
....
我已经尝试评论contracts.InsertAllOnSubmit(duplicates);
以确定没有重复的条目,但仍然会抛出异常。关于这一点的令人沮丧的部分是几天前制定的计划。数据库架构是相同的,程序没有改变,但由于某种原因,程序不再运行。
我确保Contract对象中没有任何空值。 Contract类定义为:
[Table(Name = "SDA_Contracts")]
class Contract : IEquatable<Contract>
{
[Column(IsPrimaryKey = true, IsDbGenerated = true, Name = "contractId")]
public int ContractId;
[Column(Name = "contractingParty")]
public string ContractingParty;
....
答案 0 :(得分:5)
原来我连接的是错误的数据库。我会告诉你自己。
答案 1 :(得分:0)
就我而言,我忘记设置查询中的WHERE
。