Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in entity framework code first, why is the key not unique

I have used the methods specified here to create composite keys. SQL Server calls it a PrimaryKey, but it is not unique (!). Is there a way to specify uniqueness in attributes or fluent API? I've found several hacks here but this should be possible to do upfront...

The non unique value combinations are a result of an SQLBulkCopy operation. Is it possible this is the reason?

[edit] my assumptions were wrong - read on to my answer.

like image 215
GilShalit Avatar asked Dec 09 '25 12:12

GilShalit


1 Answers

My mistake! The keys are unique, including composite keys. My problem was in the column mapping of the SqlBulCopy class. I was doing

Public Sub DoBulKCopy(dt As DataTable, cns As String)
    Dim cn As New SqlConnection(cns)
    cn.Open()
    Dim copy As New SqlBulkCopy(cn)
    For i As Integer = 0 To dt.Columns.Count - 1
        copy.ColumnMappings.Add(i,i)
    Next

While I should have been doing

Public Sub DoBulKCopy(dt As DataTable, cns As String)
    Dim cn As New SqlConnection(cns)
    cn.Open()
    Dim copy As New SqlBulkCopy(cn)
    For i As Integer = 0 To dt.Columns.Count - 1
        copy.ColumnMappings.Add(dt.Columns(i).ColumnName, dt.Columns(i).ColumnName)
    Next

And not assuming the column order is the same.

HTH

like image 162
GilShalit Avatar answered Dec 12 '25 06:12

GilShalit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!