Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

ef code first - ASP.NET MVC Many to Many relationship, using "My Own" table

I am fairly new to using Code First approach with entity framework and I know that I you have a many to many relationship like the entities below, the EF will create the intermediary table automatically:

class Post {
  ...
  public virtual ICollection<Category> Categories {get; set;}
  ... 
}

class Category {
   ...
   public virtual ICollection<Post> Posts {get; set;}
   ...
}

However, if in the intermediary table I need to have extra data fields, one possible way (which I currently like, maybe because I am unaware of better ways) would be defining a new Entity of my own, like:

class Posts_Categories {
   public int Id {get; set;}
   public int CategoryId {get; set;}
   public int PostId {get; set;}
   public string Exrtafield1 {get; set;}
   public int ex extraField2 {get; set;}
   ...
   public virtual Post Post {get; set;}
   public virtual Category Category {get; set;}
}

Using this approach, EF does create my custom intermediary table, but it also creates another one of its own called "PostsCategories" which only contains a foreign key to Post_Id and another to Category_Id.

How do I make it not create that extra one and use the one I have defined? Is this a good way to manage Many to Many relationships with extra data fields??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you should use one to many relation like this :

public class Post
{
    public System.Int32 PostId { get; set; }

    [InverseProperty("Post")]
    public virtual ICollection<Posts_Category> PostCategories { get; set; }
}

public class Category
{
    public System.Int32 CategoryId { get; set; }

    [InverseProperty("Category")]
    public virtual ICollection<Posts_Category> PostCategories { get; set; }
}

public class Posts_Category
{
    public System.Int32 PostId { get; set; }

    public System.Int32 CategoryId { get; set; }

    [ForeignKey("PostId")]
    [InverseProperty("PostCategories")]
    public virtual Post Post { get; set; }

    [ForeignKey("CategoryId")]
    [InverseProperty("PostCategories")]
    public virtual Category Category { get; set; }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...