ASP.NET MVC多对多的关系,使用和QUOT;我自己"表 [英] ASP.NET MVC Many to Many relationship, using "My Own" table

查看:249
本文介绍了ASP.NET MVC多对多的关系,使用和QUOT;我自己"表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是相当新的使用code首先与方法实体框架,我知道我你有很多像下面的实体一对多的关系时,EF会自动创建中介表:

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;}
}

使用这种方法,EF确实造成我自定义的中介表,但是也带来了自己的名为PostsCategories只包含一个外键POST_ID,另一个CATEGORY_ID的另一个。

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??

推荐答案

你应该使用一个像这样的很多关系:

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; }
}

这篇关于ASP.NET MVC多对多的关系,使用和QUOT;我自己&QUOT;表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆