从我理解我正确地做到这一点。我在表类别的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