[英]Code First Entity Framework doesn't create one to many relationship
So I have a class (Article) That is supposed to have a one-to-many relationship with another class (Category): 因此,我有一个班级(文章)应该与另一个班级(类别)具有一对多关系:
public class Article
{
[Key]
public int ArticleId { get; set;}
public virtual List<Category> Categories { get; set; }
}
public class Category
{
[Key]
public int Id { get; set;}
public string Caption { get; set;
}
When I had Code First build the Database, it generated Category having a one-to-one relationship with Article. 当我使用Code First构建数据库时,它生成的类别与Article具有一对一的关系。 This results in the the Category only being related to a single Article.
这导致类别仅与单个条款相关。 Dropping and recreating the database still generates the issue.
删除并重新创建数据库仍然会产生问题。 Any idea on what I'm doing wrong?
关于我在做什么错的任何想法吗?
1) If your Article
has many Category
, but Categories
has only one Article
: 1)如果您的
Article
有很多Category
,但是Categories
只有一个Article
:
public class Article{
private ICollection<Category> _CategoryList;
public int ArticleId { get; set;}
public virtual ICollection<Category> CategoryList {
get { return _CategoryList = _CategoryList?? new HashSet<Category>(); }
set { _CategoryList= value; }
}
}
public class Category{
public int Id { get; set;}
public string Caption { get; set;}
public Article Article { get; set;}
}
This sounds little inlogical for me. 这对我来说听起来有点不合逻辑。
2) If your Category
has many Article
, and Article
has only one Category
: 2)如果您的
Category
有很多Article
,而Article
中只有一个Category
:
public class Article{
public int ArticleId { get; set;}
public Category Category { get; set;}
}
public class Category{
private ICollection<Article> _ArticleList;
public int Id { get; set;}
public string Caption { get; set;}
public virtual ICollection<Article> ArticleList {
get { return _ArticleList= _ArticleList?? new HashSet<Article>(); }
set { _ArticleList= value; }
}
}
Note, you do not need [Key]
in case there is keyword Id
in the property name. 注意,如果属性名称中有关键字
Id
,则不需要[Key]
。 EF treats the property as Key
automatically. EF会自动将该属性视为
Key
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.