简体   繁体   中英

many to many relationship adding items

I'm using the following two classes as suggested in this website: https://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx

   public class Barca
   {
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int BarcaID { get; set; } 
    public virtual ICollection<Imbarco> Imbarco { get; set; }
    public virtual Imbarco ImbarcoBase { get; set; }
    }

   public class Imbarco
   {
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public int ImbarcoID { get; set; }
    public virtual ICollection<Barca> Barche { get; set; }
    public virtual ICollection<Barca> BaseBarche { get; set; }
    }

I need to create 1 to M relationship and for that I used these 2 navigation properties:

public virtual Imbarco ImbarcoBase { get; set; }
public virtual ICollection<Barca> BaseBarche { get; set; }

but I need also a M to M relationship and for that I used:

public virtual ICollection<Imbarco> Imbarco { get; set; }
public virtual ICollection<Barca> Barche { get; set; }

when I try to add a new item in the M to M, the bridge table is not created in the database, as described in the link reported above and also the edmx file I tried to generate in VisualStudio created a 0..1 to M and a M to 0..1 relationship instead of m to M. What am I doing wrong ?

I would start by fixing your model. I recommend you configure with fluent api , but you can try the InverseProperty annotation so EF makes the proper connections:

   public class Imbarco
   {
       [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
       public int ImbarcoID { get; set; }

       [InverseProperty("Imbarco")]
       public virtual ICollection<Barca> Barche { get; set; }
       [InverseProperty("ImbarcoBase")]
       public virtual ICollection<Barca> BaseBarche { get; set; }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM