2012-09-02 69 views
0

昨天醒來想知道MVC所有的大驚小怪。所以我發現,哇,這很好,像這樣的東西。通過鏈接MVC4模型ID

我習慣於在ASP.NET項目中使用一個相關的Linq to Sql DataContext DB。

//Some ASP.NET Page Codebehind 
DataContext dbEntire = new DataContext() 

隨着MVC4與實體框架,你做模型,它會爲你創建一個數據庫。

//Models/Article/Article.cs 
public class ArticleDBContext: DbContext 
{ 
    public DbSet<Article> Articles { get; set; } 
} 
public class Article 
{ 
    public int ID {get;set;} 
    public string Title{ get; set; } 
    public int AuthorID { get; set; } 
    public string Body { get; set; } 
    public int CategoryID { get; set; } 
    public DateTime Submitted{ get; set; } 
    public DateTime LastModified { get; set; } 
} 

作者和分類是單獨的模型。

但是,你如何建立所有的數據庫關係..一對多等等等等?

回答

0
public class ArticleDBContext: DbContext 
{ 
    public DbSet<Article> Articles { get; set; } 
    public DbSet<Category> Categories { get; set; } 
} 

public class Article 
{ 
    public int ID {get;set;} 
    public string Title{ get; set; } 
    public int AuthorID { get; set; } 
    public string Body { get; set; } 

    public int CategoryID { get; set; } 
    public virtual Category Category { get; set; } 

    public DateTime Submitted{ get; set; } 
    public DateTime LastModified { get; set; } 
} 

public class Category 
{ 
    public int ID {get;set;} 
    public string Name{ get; set; } 
    public virtual ICollection<Article> Articles { get; set; } 
} 

請閱讀關於實體框架代碼的一些教程。

EF Code First and MVC

EF getting started