0

From what I understand I am doing this correctly. I have a blog table with a relationship of CategoryId on the table Category's id field. But I can not get it to resolve within my controller when I use the .include() command. Here is the code.

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
  • 1
    Should this be public virtual Category Category { get; set; } instead of public virtual ICollection<Category> Category { get; set; } ? Commented Mar 23, 2013 at 17:26

2 Answers 2

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

Should work better.

Sign up to request clarification or add additional context in comments.

Comments

1

Instead of

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

I think it should be

public virtual Category Category { get; set; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.