I have table Articles which has ability to have LinkedArticles, so basically when user is previewing for example "Iphone 13" linked article could be "Iphone Charger" or "AirPads" etc.
Here are my entites:
public class Article : BaseEntity<long>, IDeleted
{
public long? BrandId { get; set; }
public Brand Brand { get; set; }
public string Title { get; set; }
public string ShortDescription { get; set; }
public string Description { get; set; }
public ICollection<LinkedArticle> LinkedArticles { get; set; }
public bool Deleted { get; set; }
}
Linked article looks like this:
public class LinkedArticle : BaseEntity<long>, IDeleted
{
public long ArticleId { get; set; }
public Article Article { get; set; }
public long RelatedArticleId { get; set; }
public Article RelatedArticle { get; set; }
public bool Deleted { get; set; }
}
So basically I wanted to hold related articles in this table LinkedArticles so for example article id 5 can have few different articles as related to that with id 5.
But when I try to add a migration I got following error:
Unable to determine the relationship represented by navigation 'Article.LinkedArticles' of type 'ICollection'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
What is happening here? I've added ICollection<LinkedArticle>
to Article.cs
because I wanted to have ability to query linked articles from article entity.
CodePudding user response:
You can have a Reference from Article to Article. Have a look here:
FK to the Same Table Code First Entity Framework
Then you don't need a separate LinkedArticle Entity.
CodePudding user response:
This should be many to many relationship. Article can have many linked articles, but linked article can be linked to many articles.
Take a look at this docs: https://docs.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api,fluent-api-simple-key,simple-key#many-to-many
For example (post can have many tags, but tag can be assigned to many posts):
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public ICollection<Tag> Tags { get; set; }
}
public class Tag
{
public string TagId { get; set; }
public ICollection<Post> Posts { get; set; }
}