EF Code First自引用复合键

时间:2017-12-11 09:58:08

标签: c# asp.net-mvc code-first

我正在制作EF代码第一个用于存储文章的MVC模型。

每篇文章都有多个页面,所以我把密钥作为ID和页码的复合键。

我也希望文章有子文章,所以我希望文章能够用外键自我引用。

由于密钥是复合密钥,我正在努力进行自我引用。当我构建模型并尝试使用控件时,我得到了System.StackOverflowException'

public class Article
    {

        [Key, Column(Order = 0)]
        public int ArticleID { get; set; }

        [Key, Column(Order = 1)]
        public int ArticlePageNo { get; set; }

        public string ArticleTitle { get; set; }

        public string ArticleBody { get; set; }

        [ForeignKey("ArticleID, ArticlePageNo")]
        public Article ArticleParent { get; set; }
    }

2 个答案:

答案 0 :(得分:1)

在这种情况下,我确实认为你没有正确使用EF。 如果我理解你的代码,EF将尝试将对象引用到自身,如果你正在使用一个急切的加载方案,那将导致Stackoverflow异常。因此,您实际上是在Article和Article之间定义了1对1的关系,将主键和外键都指定为由ArticleID和ArticlePageNo组成的复合键。 EF不能消化。 我建议你重新构建你的数据:所以你在文章和页面之间有一对多的关系,文章和文章之间有一对多的关系。代码看起来像这样:

public class Article
{
    // object unique ID
    public int Id { get; set; }
    public string Title { get; set; }

    // parent Id used as foreign key
    public int? ParentArticleId { get; set; }
    // navigational property for parent
    public virtual Article ParentArticle { get; set; }
    // navigational property for children
    public virtual ICollection<Article> Articles { get; set; }
    // navigational property for article pages
    public virtual ICollection<ArticlePage> Pages { get; set; }
}

public class ArticlePage 
{
    // object unique ID
    public int Id { get; set; }
    public string PageBody { get; set; }

    // parent Id used as foreign key
    public int ArticleId { get; set; }
    // navigational property for parent article
    public virtual Article { get; set; }
}

答案 1 :(得分:0)

这个模型实现了我试图做的事情,但是根据反馈,我可能会重新考虑我的方法。

.closest('li')
相关问题