Home > OS >  How to insert data during many-to-many relationship
How to insert data during many-to-many relationship

Time:11-08

lets say we have two classes(these are just sample classses):

public class Post
{
    public int ID { get; set; }
    public string Text { get; set; }
    public virtual ICollection<Tag> Tags { get; set; } 
}

public class Tag
{
    public int ID { get; set; }
    [Required]
    public string Label { get; set;}
    public virtual ICollection<Post> Posts { get; set; } 
}

P.S after execution "PostTag" table is created in database.

So in my current database there is the following situation: I have separate service for getting "Posts" and I am writing this data directly to database.(lets say we have 500 records in database. P.S these are max number of "Posts" I will be working around).

Then I have service for "Tag". This service does the following: I am getting data of "Tags" from API**(It is about 1500 records)**, which is collection and each "Tag" contains its own "Post" collection in returned data (lets say each "Tag" has 100 records of "Posts").

So the problem is that, after I get all the "Tags" and then write them in database, in "Post" tables, "Posts" that was returned during "Tag" service are also written in table, I mean before calling "Tag" service, If we had 500 records, now we have 15000 500 and that is wrong.

I want to happen following: when I call "Tag" service, it should just write "Tags" in database table and instead of adding "Posts" in table, use already written data in "Posts" table in order to set up relationship in "PostTag" table.

So in tables there should be this kind of situation: Post - 500 records, Tags - 1500 records and PostTag - the amount of records that are needed for relationship

How can I accomplish that?

CodePudding user response:

There a Problem with your entities

Post Table dont contain tags. but its will contain PostTag table id.

Note If you already have table PostTag in database. you can still map it by simply defining class in your dbcontext

 public class Post
    {
        public int ID { get; set; }
        public string Text { get; set; }
        public virtual ICollection<Tag> Tags { get; set; } 
    }
    
    public class Tag
    {
        public int ID { get; set; }
        [Required]
        public string Label { get; set;}
        public virtual ICollection<PostTag> PostTags { get; set; } 
    }

public class PostTag
    {
        public int ID { get; set; }
        public virtual Tag Tag { get; set; }
        public int TagId { get; set; }
        public int PostId { get; set; }
        public virtual Post Post { get; set; }
    }

CodePudding user response:

If you have two entities with many-to-many relationship, you have to make a new class that connects the other two classes. You should include primary keys (of the other classes) and additional features that describe that connection (in most cases).

  • Related