据我了解,我这样做是正确的。我在表 Category 的 id 字段上有一个与 CategoryId 关系的博客表。但是当我使用 .include() 命令时,我无法在我的控制器中解决它。这是代码。
博客.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; }
}
类别.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; }
}
博客控制器
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());
}
}