Good day, I want to set a composite alternate key in the database for the fields, how can this be done through the attributes of the Entity Framework? There is another idea to try through migration, but it is preferable through attributes, the search did not give the presence of such an attribute, maybe it was looking bad?

ps. EF6, .Net, C #, code first

1 answer 1

The Microsoft documentation says:

Alternate keys can not be configured using Data Annotations.

Translation from me:

Alternative keys cannot be configured using data annotation, i.e. attributes.

Since you are using Code-First, I recommend trying Fluent API.

I will give an example of setting up one property using Fluent API ^

class MyContext : DbContext { public DbSet<Car> Cars { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Car>() .HasAlternateKey(c => c.LicensePlate); } } class Car { public int CarId { get; set; } public string LicensePlate { get; set; } public string Make { get; set; } public string Model { get; set; } } 

Full list of attributes supported by EF:

  • As far as I read and tried, this option is suitable for EF core, and in EF6 there is no ModelBuilder class (it is now called DbModelBuilder), and it does not have the HasAlternateKey method. Regarding alternative keys, there are entries that will be implemented in EF7. In the meantime, I ’m probably implementing it through a composite primary key, which I don’t want to - sag3ll0