问题描述
我对在实体框架中使用 Code First 方法相当陌生,而且我知道我与下面的实体有多对多关系,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 多对多关系,使用“我自己的"桌子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!