1

I have a composite key mapped in a class as shown:

HasKey(l => new { l.A, l.B });

But, here A is supposed to be an identity.

Property(l => l.A).HasColumnName("A").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(l => l.B).HasColumnName("B");

However, when I try to Add an object with the value of A(null since it is an identity) and B, I get a Primary Key violation.

Is there any way to get around this?

The types are as follows:

public Int64? A{ get; set; } //Identity
public int B { get; set; }

And from a DB world:

A   bigint
B   int
Mkl Rjv
  • 6,815
  • 5
  • 29
  • 47

2 Answers2

2

In the case where the Key field is an Integer, Code First defaults to DatabaseGeneratedOption.Identity, so, A and B are Identity by default. You need to specify B is not Identity. Try with this configuration:

Property(l => l.A).HasColumnName("A");
Property(l => l.B).HasColumnName("B").HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

BTW, why A is nullable?. A PK defines a unique identifier for every row in a table, so, due to A is Identity, you always going to have a value in that column when you insert a new row in your table.

ocuenca
  • 38,548
  • 11
  • 89
  • 102
0

It seems like it's not allowed to have null values even in composite primary keys. As mentioned here, the workaround would be to define a separated Id column as primary key.

Community
  • 1
  • 1
Kamyar
  • 18,639
  • 9
  • 97
  • 171