表示实体框架中的帮助表

时间:2011-09-20 21:06:32

标签: c# entity-framework entity-framework-4.1 ef-code-first

表1:文章

表2:ArticleCategories

我如何表示两个表之间的关系,这是1-> 1的关系:

我可以做到以下几点,但我不确定这是正确的方法:

public class Article
{
    public int ArticleIndex { get; set; }
    public int Category { get; set; }
    public Guid User { get; set; }
    public int Parent { get; set; }
    public int Level { get; set; }
    public int Order { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime DateExpires { get; set; }
    public bool Show { get; set; }   
    public string Title { get; set; }
    public string TitleHtml { get; set; }
    public string Content { get; set; }
    public string ContentHtml { get; set; }
    public string ShortTitle { get; set; }
    public ArticleCategory Category { get; set; }
}

public class ArticleCategory
{
    public int CategoryIndex { get; set; }
    public string Name { get; set; }
}

1 个答案:

答案 0 :(得分:0)

按照惯例,Code First期望每个类/表都有Id属性。然后你可以做这样的事情:

public class Article
{
    public int Id { get; set; }
    public int ArticleIndex { get; set; }
    public int Category { get; set; }
    public Guid User { get; set; }
    public int Parent { get; set; }
    public int Level { get; set; }
    public int Order { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime DateExpires { get; set; }
    public bool Show { get; set; }   
    public string Title { get; set; }
    public string TitleHtml { get; set; }
    public string Content { get; set; }
    public string ContentHtml { get; set; }
    public string ShortTitle { get; set; }
    public int ArticleCategoryId { get; set; }

    public virtual ArticleCategory ArticleCategory { get; set; }
}

public class ArticleCategory
{
    public int Id { get; set; }
    public int CategoryIndex { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Article> Articles { get; set; }
}

请注意virtual关键字。 EF Code First需要这样才能在幕后发挥其魔力。

现在,如果您正在使用Article,则可以通过article.ArticleCategory获取所有类别信息,如果您有ArticleCategory,则可以找到它引用的文章使用articleCategory.Articles.Single()

有关详细信息,请参阅Scott Gu撰写的这篇文章:

http://weblogs.asp.net/scottgu/archive/2010/12/08/announcing-entity-framework-code-first-ctp5-release.aspx