Base solution for your next web application
Open Closed

How to make composite unique key? #3868


User avatar
0
manojreddy created

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.


1 Answer(s)
  • User Avatar
    0
    strix20 created

    What you are looking for is not a key. You can only have a single key per table.

    It sounds like you want a unique Index. EF Core does not support indices via attributes, so you must define the index with fluent API.

    Alternatively you can simply disable automatic migrations, and write the SQL yourself (which in my opinion, you should always do. From an architecture standpoint, you should be writing SQL yourself and managing it with a db script management system like DBUp or FlyWay.)

    Here is an example of how to do the indices via Fluent Api in EF Core:

    [https://stackoverflow.com/questions/41246614/entity-framework-core-add-unique-constraint-code-first])