Defining many to many relation in code first entity framework

前端 未结 3 476
孤独总比滥情好
孤独总比滥情好 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:56

    Try doing it like this:

    [Table("UserProfile")]
    public class UserProfile
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
    
        public string UserName { get; set; }
    
        [InverseProperty("UserProfiles")]
        public IList<MartialArt> MartialArts { get; set; }
    }
    
    [Table("MartialArt")]
    public class MartialArt
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
    
        public string Name { get; set; }
    
        public string Description { get; set; }
    
        public string IconPath { get; set; }
    
        public string ImagePath { get; set; }
    
        [InverseProperty("MartialArts")]
        public IList<UserProfile> UserProfiles { get; set; }
    }
    
    0 讨论(0)
  • 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<UserProfile>()
        .HasMany(b => b.MartialArts)
        .WithMany(a => a.UserProfiles)
        .Map(m => m.MapLeftKey("MartialArtId")
            .MapRightKey("UserProfileId")
            .ToTable("UserProfileToMartialArt"));
    

    In MartialArts Model put

    public IList<UserProfile> UserProfiles { get; set; }   
    

    In UserProfile Model put

    public IList<MartialArt> MartialArts { get; set; }  
    
    0 讨论(0)
  • 2021-02-06 14:15

    In EntityFramework 6.1, you don't need to do any of this - just add collections of the two types to each class and everything falls into place.

    public class UserProfile {
        public int Id { get; set; }
        public string UserName { get; set; }
        public virtual ICollection<MartialArt> MartialArts { get; set; }
    
        public UserProfile() {
            MartialArts = new List<MartialArt>();
        }
    }
    
    public class MartialArt {
        public int Id { get; set; }
        public string Name { get; set; }
        // *snip*
        public virtual ICollection<UserProfile> UserProfiles { get; set; }
    
        public MartialArt() {
            UserProfiles = new List<UserProfile>();
        }
    }
    
    0 讨论(0)
提交回复
热议问题