I want to have a 2 alternate keys with this scenario :
public class A { public int Id {get;set} } public class B:A { public int OtherPropertyKey {get;set} public string Name {get; set} }
DbContext and ExtensorMethod :
public class CContext : DbContext { public DbSet<B> Bs{ get; set; } public CContext (DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfigurationsFromAssembly(); base.OnModelCreating(modelBuilder); } } public static class EfExtensions { public static void ApplyConfigurationsFromAssembly(this ModelBuilder modelBuilder) { var allClasses = AllClasses.FromLoadedAssemblies().ToList(); var conftypes = allClasses.Where(t => !t.IsInterface && !t.IsAbstract && t.GetInterfaces() .Where(i => i.IsGenericType) .Select(i => i.GetGenericTypeDefinition()) .Any(i => i == typeof(IEntityTypeConfiguration<>))) .Select(t => new { ConfigType = t, //EntityType = //t.GetInterfaceGenericArguments(typeof(IEntityTypeConfiguration<>)).Single() }).ToArray(); foreach (var conf in conftypes) { dynamic confInstance = Activator.CreateInstance(conf.ConfigType); modelBuilder.ApplyConfiguration(confInstance); } } }
Implementation of IEntityTypeConfiguration:
public class BConfiguration : IEntityTypeConfiguration<B> { public void Configure(EntityTypeBuilder<B> builder) { builder.HasKey(b => new {b.Id, b.OtherPropertyKey}); builder.Property(b => b.Id).ValueGeneratedOnAdd(); builder.Property(b => b.OtherPropertyKey).ValueGeneratedOnAdd(); } }
When I do a migration with command dotnet I get this:
migrationBuilder.CreateTable( name: "B", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(nullable: true) }, constraints: table => {table.PrimaryKey("PK_Bs", x => x.Id); /// I want two PK like : table.PrimaryKey("PK_Bs", x => x.Id);
/// table.PrimaryKey("PK_Bs", x => x.OtherPropertyKey); });
Whay do I got that ??? What do I doing wrong ???