從我理解我正確地做到這一點。我在表類別的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());
}
}
如果這是公共虛擬分類分類{獲取;組; }而不是公開的虛擬ICollection類別{get;組; }? –
christiandev
2013-03-23 17:26:43
是的你是正確的謝謝你 – 2013-03-23 17:32:31