2
public class Article
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string Title { get; set; }
    [Required]
    public string Lead { get; set; }
    [Required]
    public string Content { get; set; }
    [Required]
    public bool IsPublished { get; set; }

    public int CategoryId { get; set; }
    public Category Category { get; set; }
    public IList<ArticleTags> ArticleTags { get; set; }
}

public class Tag
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }

    public IList<ArticleTags> ArticleTags { get; set; }
}


public class ArticleTags
{
    public int ArticleId { get; set; }
    public Article Article { get; set; }

    public int TagId { get; set; }
    public Tag Tag { get; set; }
}

Why won't this rest request work?

{
    "Title":"tit",
    "Lead":"lead",
    "Content":"c ",
    "IsPublished":false,
    "Category":{
        "Name":"Cat"
    },
    "ArticleTags":[
        {
            "Name":"tag1"
        },
        {
            "Name":"tag2"
        }   
    ]

}

Getting this error

The property ArticleId on entity type ArticleTags has a temporary value. Either set a permanent value explicitly or ensure that the database is configured to generate values for this property.

Ideally, I'd like my rest request to look like this

{
    "Title":"tit",
    "Lead":"lead",
    "Content":"c ",
    "IsPublished":false,
    "Category":{
        "Name":"Cat"
    },
    "ArticleTags":[
        1,2,3,4,5   
    ]

}

where I can just put ids of already existing tags, how should I write my many to many relationship then?

Should I change my approach and create ArticleRest class and just take list of tag ids and then manually insert them into my ArticleTags table?

ekad
  • 14,436
  • 26
  • 44
  • 46
ilovekittens
  • 75
  • 1
  • 6

1 Answers1

0

Something to consider is Many to Many relationships are not supported in EF Core so you need a Join Table which it seems you do have.

So the other thing is you might not have setup the Foreign key relationship up from Article to your ArticleTags

The script should look something like this:

CREATE TABLE [dbo].[ArticleTags] (
[ArticleTagId] INT IDENTITY(1,1) NOT NULL,
[ArticleId]    INT NOT NULL,
[TagId]        INT NOT NULL,
CONSTRAINT [PK_ArticleTags_ArticleTagId] PRIMARY KEY CLUSTERED ([ArticleTagId] ASC),
CONSTRAINT [FK_Article_ArticleId_ArticleTags_ArticleId] FOREIGN KEY ([ArticleId]) REFERENCES [dbo].[Article] ([ArticleId]),
CONSTRAINT [FK_Tag_TagId_ArticleTags_TagId] FOREIGN KEY ([TagId]) REFERENCES [dbo].[Tag] ([TagId]),
)

Should solve the problem.

If not giving this a read should help

HenryMigo
  • 164
  • 1
  • 7