【问题标题】:represent a help table in entity framework表示实体框架中的帮助表
【发布时间】:2011-09-20 21:06:32
【问题描述】:

表 1:文章

表 2:文章类别

如何表示两个表之间的关系是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->Many 关系吗? 一个分类有很多篇文章,一篇文章属于一个分类?
  • 你是对的,我的错……这是一对多的关系

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


【解决方案1】:

按照惯例,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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-30
    • 2019-07-18
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 2011-05-21
    • 2018-11-03
    • 1970-01-01
    相关资源
    最近更新 更多