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 });
}
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; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With