1

I have a table which has the Id as primary key, I want to have a composite unique key on Code and Value column. I'm trying in this way.

[Table("Test")]

public class Test: FullAuditedEntity

{


[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public virtual int Code { get; set; }

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public virtual int Value { get; set; }

But it's making the composite primary key not unique key.

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197

2 Answers2

1

Try this:

public class SomeClass : Entity<int>
{
    [Column("Code")]
    public override int Id {get; set;}

    public virtual string Name { get; set; }    
}

[DatabaseGenerated(DatabaseGeneratedOption.None)] will make the Database to NOT create the Code column. What you need in reality is to override the Id and rename it to Code.

And to have a composite key, simply add

[Key]
public virtual int Value { get; set; }

field.

Sleek
  • 211
  • 3
  • 11
1

Adding solution for others.

Don't modify anything just add the below line

modelBuilder.Entity<Test>(b =>
        {
            b.HasIndex(e => new { e.Code, e.Value}).IsUnique();
        });
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197