I'm trying to create many to many relationship with EF core. That's my 2 entries:
public class DbCharacter : DbEntity
{
public string CharName { get; set; }
public ICollection<DbCharacterSkill> Skills { get; set; }
}
public class DbSkill : DbEntity
{
public string SkillName { get; set; }
}
public class DbCharacterSkill : DbEntity
{
public int CharacterId { get; set; }
public int SkillId { get; set; }
public DbCharacter Character { get; set; }
public DbSkill Skill { get; set; }
}
public class DatabaseContext : DbContext
{
...
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Many to many relations.
modelBuilder.Entity<DbCharacterSkill>().HasKey(x => new { x.CharacterId, x.SkillId });
modelBuilder.Entity<DbCharacterSkill>().HasOne(pt => pt.Character).WithMany(p => p.Skills).HasForeignKey(pt => pt.CharacterId);
}
}
That should work, but I'm getting an exception while Update-Database
:
Failed executing DbCommand (26ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE CharacterSkill
(
CharacterId
int NOT NULL,
SkillId
int NOT NULL,
Id
int NOT NULL AUTO_INCREMENT,
CONSTRAINT PK_CharacterSkill
PRIMARY KEY (CharacterId
, SkillId
),
CONSTRAINT FK_CharacterSkill_Characters_CharacterId
FOREIGN KEY (CharacterId
) REFERENCES Characters
(Id
) ON DELETE CASCADE,
CONSTRAINT FK_CharacterSkill_Skills_SkillId
FOREIGN KEY (SkillId
) REFERENCES Skills
(Id
) ON DELETE CASCADE
);
MySql.Data.MySqlClient.MySqlException (0x80004005): Incorrect table definition; there can be only one auto column and it must be defined as a key
This is obviously saying, that only Id can be a primary key because it's auto-incremented. But all tutorials, that I read, were saying, that I have to write something like modelBuilder.Entity<DbCharacterSkill>().HasKey(x => new { x.CharacterId, x.SkillId });
.
QUESTION: What will happen if I don't use HasKey? Or what is the right approach to work with many to many and MySQL?
User contributions licensed under CC BY-SA 3.0