Defining many to many relation in code first entity framework

前端 未结 3 478
孤独总比滥情好
孤独总比滥情好 2021-02-06 13:45

I have 3 classes in my model as you can see below.

[Table("UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseG         


        
3条回答
  •  [愿得一人]
    2021-02-06 13:58

    If I understand you are simply trying to create a many to many with a transitive table. If so this is another way to approach this. Use Fluent API to map as below. You can change the UserProfileToMartialArt to whatever you want the table name to be. Instead of creating the MartialArtUserProfile model let EF create the middle ground for you. This also specifies your keys which should get you around the error.

    modelBuilder.Entity()
        .HasMany(b => b.MartialArts)
        .WithMany(a => a.UserProfiles)
        .Map(m => m.MapLeftKey("MartialArtId")
            .MapRightKey("UserProfileId")
            .ToTable("UserProfileToMartialArt"));
    

    In MartialArts Model put

    public IList UserProfiles { get; set; }   
    

    In UserProfile Model put

    public IList MartialArts { get; set; }  
    

提交回复
热议问题