skip to Main Content

I want to provide association between Blog and Category but I can’t find where I went wrong

Here’s how I make(List<Blog>) the category page to get the association
enter image description here

This is my blog page
enter image description here

But when I migrate and update the database, there is no association between them.

i want to know where i might have gone wrong about this

sql image like this
enter image description here

2

Answers


  1. I assume that you are using migrations.

    You can try removing the reference from Category to Blog, by removing the public List<Blog> Blogs property.
    The reason is that in your current code you have a bi-directional relationship (Blog references Category, and Category references Blog), and that is not well handled by Entity Framework.

    If in your code you need to find all the blogs belonging to a particular category, you can do something like

    var blogs = Blogs.Where(b => b.CategoryID == categoryId);
    

    (where categoryId is the ID of the category you want to find blogs for)

    Login or Signup to reply.
  2. in Blog class you can add ForiegnKeyAttribute to determine the property Category is assosiated with CategoryId.
    Like this:

    [ForeignKey("CategoryId")]
    public Category Category { get; set; }
    

    and also it’s better to use ICollection instead of List so change Category class like this:

    public ICollection<Blog> Blogs { get; set; }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search