2013-03-23 150 views
0

从我理解我正确地做到这一点。我在表类别的id字段中有一个具有CategoryId关系的博客表。但是当我使用.include()命令时,我无法在控制器中解决它。这是代码。ASP.Net MVC实体框架关系

Blog.cs

public class Blog 
{ 
    [Key] 
    public int Id { get; set; } 
    [Required, StringLength(50)] 
    public string Title { get; set; } 
    [DataType(DataType.Date)] 
    public DateTime PostedDate { get; set; } 
    [Required] 
    public string Meat { get; set; } 
    [Required, StringLength(25)] 
    public int CategoryId { get; set; } 
    public string FriendlyUrl { get; set; } 

    public virtual ICollection<Category> Category { get; set; } 
} 

public partial class BlogDbContext : DbContext 
{ 
    public DbSet<Blog> Blogs { get; set; } 
} 

Category.cs

public class Category 
{ 
    [Key] 
    public int Id { get; set; } 
    [Required, StringLength(50)] 
    public string Title { get; set; } 
    public string FriendlyUrl { get; set; } 
} 

public partial class BlogDbContext : DbContext 
{ 
    public DbSet<Category> Categories { get; set; } 
} 

BlogController

public class BlogController : Controller 
{ 
    private readonly BlogDbContext _db = new BlogDbContext(); 

    public ActionResult Index() 
    { 
     var blogs = _db.Blogs.Include(c => c.Category); //This is where the error occurs 
     return View(blogs.ToList()); 
    } 
} 

The relationship in my SQL Server 2012 Database

+1

如果这是公共虚拟分类分类{获取;组; }而不是公开的虚拟ICollection 类别{get;组; }? – christiandev 2013-03-23 17:26:43

+0

是的你是正确的谢谢你 – 2013-03-23 17:32:31

回答

3
var blogs = _db.Blogs.Include("Category"); 

应该更好。

+0

和繁荣去炸药谢谢你! – 2013-03-23 17:33:19

1

而不是

public virtual ICollection<Category> Category { get; set; } 

我觉得应该是

public virtual Category Category { get; set; }