2012-09-02 64 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