0

据我了解,我这样做是正确的。我在表 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());
    }
}

我的 SQL Server 2012 数据库中的关系

4

2 回答 2

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

应该工作得更好。

于 2013-03-23T17:26:39.223 回答
1

代替

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

我认为应该是

public virtual Category Category { get; set; }
于 2013-03-23T17:33:48.763 回答