如何使用 EntityFramework 在 asp.net MVC 中映射多对多关系?

How to use EntityFramework to map a many to many relationShip in asp.net MVC?

我从 EF with MVC 中读到一篇 post。该示例使用了三个具有一对多关系的表。并且设置了StudendId作为外键,我可以在视图中直接调用Model.Enrollments(模型是Student类型)。 我想知道如何建立两个表的多对多关系。

开头为:

public class Post
{
    public int Id
    { get; set; }

    public int CategoryId
    { get; set; }
    public string Title
    { get; set; }

    public string ShortDescription
    { get; set; }

    public string Description
    { get; set; }

    public virtual ICollection<Tag> Tags
    { get; set; }
}
public class Tag
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int TagId
    { get; set; }

    public string Name
    { get; set; }

    public string UrlSlug
    { get; set; }

    public string Description
    { get; set; }

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

我想调用 Model.Tags 获取与 Post 相关的所有标签,或调用 Model.Posts 获取属于某个标签的所有 Post在视图中。我想我需要 class 类似

的东西
public class TagPost
{
    public int TagId{get;set;}
    public int PostId{get;set;}
}

但是好像TagIdPostId都是外键?我不知道该怎么做。

阅读中:

var post1 = dbContext.Post.FirstOrDefault(x => x.PostId ==1);
 var tags = post1.Tags(); 

正在插入:

// Create a New Post Entity
var post = new Post();

// Assign it you values either from ViewModel or
    post.Title ="ManyToMany";
// Create your list of tags related to Post
    post.Tags = new List<Tags>();

// Add a Tag from Database to this List where TagId == 1
    post.Tags.Add(dbContext.Tags.First(s => s.TagId == 1));

// save Changes
    dbContext.SaveChanges();

保存更改后,您会看到在多对多映射中 table 有一条新记录

PostId = 2 // Considering you have PostId == 1 already in DB
TagId = 1 // Tag you added before dbContext.SaveChanges()