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. 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
:
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
:
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. EF treats the property as Key
automatically.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.