I have a table (Id, name, itemst, otherproperties), Id is the primary key and I want a unique composite key (name, itemst). How can I add this using code first either by flu
Let say you have a entity named
public class MyTable
{
public int Id {get; set;}
public String Name {get; set;}
}
you can create composite key using
public class YourContext : DbContext
{
public DbSet MyTables { get; set; }
protected override void OnModelCreating(DbModelBuilder builder)
{
builder.Entity().HasKey(table => new {table.Id, table.Name});
}
}
if you prefer data annotation you can simple add KeyAttribute
to multiple properties
public class MyTable
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] // optional
[Key]
public int Id { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.None)] // optional
[Key]
public String Name { get; set; }
}