2013-03-23 190 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; }