简体   繁体   中英

Unable to determine relationships - Entity Framework Core

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.

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.

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%2Cfluent-api-simple-key%2Csimple-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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM