2011-09-20 39 views
0

表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; } 
} 
+0

您是否使用代碼第一次? – devuxer

+0

是............................................ – user560498

+1

不要你的意思是一個1->多種關係? *一個*類別有*許多*文章和一篇文章屬於*一個*類別? – Slauma

回答

0

按照慣例,代碼第一次預計的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()什麼文章。

欲瞭解更多信息,請參見本文由斯科特谷:

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