Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The entity type has multiple properties with the [Key] attribute. Composite primary keys can only be set using 'HasKey' in 'OnModelCreating'.'

I have this table which has 2 columns to form the composite key. I am using EF Core. So this is my model

public class MyModel
{
    [Key]
    [Column(Order = 0)]
    [StringLength(255)]
    public string column1 { get; set; }

    [Key]
    [Column(Order = 1)]
    [StringLength(255)]
    public string column2 { get; set; }
}

When I run the xunit test, I got this error

The entity type xxx has multiple properties with the [Key] attribute. Composite primary keys can only be set using 'HasKey' in 'OnModelCreating'.'

This is the code for xunit.

    public MyServicesTest()
    {
        var options = new DbContextOptionsBuilder<MyContext>();
        options.UseSqlServer(myServiceSqlConnStr);

        _myServicesContext = new MyContext(options.Options);

        _myServicesContext.Database.EnsureDeleted();

    }

Error is from _myServicesContext.Database.EnsureDeleted();

This is my context classs

public class MyContext : DbContext
{
    public MyContext(DbContextOptions<MyContext> options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.ApplyConfigurationsFromAssembly(typeof(MyContext).Assembly);
        
    }
}

I have tried to use OnModelCreating in MyContext but still the same error.

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {            
        modelBuilder.Entity<MyModel>()
              .HasKey(m => new { m.column1 , m.column2 });
    }
like image 733
Steve Avatar asked Dec 22 '25 19:12

Steve


1 Answers

In EF7 You can use [PrimaryKey] Attribute on your model class.

[PrimaryKey(nameof(column1), nameof(column2))]
public class MyModel
{
    [Column(Order = 0)]
    [StringLength(255)]
    public string column1 { get; set; }

    [Column(Order = 1)]
    [StringLength(255)]
    public string column2 { get; set; }
}
like image 96
Sufyan Nisar Avatar answered Dec 24 '25 09:12

Sufyan Nisar



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!