1

I have an entity JournalEntry which has a many-to-many relationship with Tags thorugh a jointable JournalEntryTags.

I want to create a journalentry uppon submittion of a form containing the journal content and a comma separated list of tags. If the tags does not exist in the db, they should be created. The relationship between the journalentry and new and old tags should be created.

This is the AddEntry method I've got in my JournalEntryRepository:

    public void AddEntry(JournalEntry journalEntry, string tags)
    {
        journalEntry.CreatedAt = DateTime.Now;
        _appDbContext.JournalEntries.Add(journalEntry);
        
        
        var tagsArray = tags.Split(',');
        foreach (string tag in tagsArray)
        {
            if (_tagRepository.GetTagByName(tag.Trim()) is null)
            {
                _tagRepository.AddTag(new Tag { Name = tag.Trim() });
            }

        }

        _appDbContext.SaveChanges();
    }

How do I create the relationship JournalEntryTags from here? What do I need to know in order to make that happen?

2 Answers 2

2

It can be divided into the following steps. I used a Post-Tag (many-to-many) example to illustrate.

Model:

public class Post
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public List<PostTag> PostTags { get; set; }
}

public class PostTag
{
    
    public int PostId { get; set; }
    public int TagId { get; set; }
    [ForeignKey("PostId")]
    public Post Post { get; set; }
    [ForeignKey("TagId")]
    public Tag Tag { get; set; }
}

public class Tag
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public List<PostTag> PostTags { get; set; }
}

1.Add the post, and get the new added postId

2.Traverse the tagArray, determine whether the tag already exists in the database, if not, add it.

3.After inserting the new tags, get the ids of the tags in tagArray.

4.Assign postId and tagId to posttag(the join table), then store it to database.

public IActionResult AddPost()
{
    var post = new Post
    {
        Name = "AA"
    };
        
    var tags = "tag1,tag3,tag4";
    var tagsArray = tags.Split(',');
    var existTagsName = _db.Tags.Select(t => t.Name).ToList();
        
    

    _db.Posts.Add(post);
    _db.SaveChanges();

    int postId = post.Id;

    foreach (string tag in tagsArray)
    {
        if (!existTagsName.Contains(tag))
        {
            var newTag = new Tag();
            newTag.Name = tag;
            _db.Tags.Add(newTag);
               
        }
    }

    _db.SaveChanges();

        
    foreach (string tag in tagsArray)
    {
        var postTag = new PostTag();
        var tagId = _db.Tags.Where(t => t.Name == tag).Select(t => t.Id).FirstOrDefault();
        postTag.PostId = postId;
        postTag.TagId = tagId;
        _db.PostTags.Add(postTag);
    }
    _db.SaveChanges();

    return View();
}
Sign up to request clarification or add additional context in comments.

Comments

1

You need to iterate over your newly created tags and manually create a JournalEntryTags object, giving it a reference to the appropriate JournalEntry and Tag object.

Then you just addi it to the collection in your database context and save the changes.

I also recommend implementing this with editing in mind: you should first get existing relations between your current entry and various tags, remove those not present in your new list of tags, then create the ones that do not yet exist.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.