【问题标题】:Create entity, relationship and related entity at the same time in .net core MVC在.net core MVC中同时创建实体、关系和相关实体
【发布时间】:2021-02-09 05:28:38
【问题描述】:

我有一个实体 JournalEntry,它通过可连接的 JournalEntryTags 与标签具有多对多关系。

我想在提交包含日记内容和逗号分隔的标签列表的表单后创建一个日记条目。如果数据库中不存在标签,则应创建它们。日志条目和新旧标签之间的关系应该建立起来。

这是我的 JournalEntryRepository 中的 AddEntry 方法:

    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();
    }

如何从这里创建关系 JournalEntryTags?为了实现这一目标,我需要知道什么?

【问题讨论】:

    标签: c# .net asp.net-core entity-framework-core asp.net-core-mvc


    【解决方案1】:

    可以分为以下几个步骤。我使用了一个 Post-Tag(多对多)示例来说明。

    型号:

    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.添加帖子,获取新添加的postId

    2.遍历tagArray,判断标签是否已经存在于数据库中,如果不存在则添加。

    3.插入新标签后,获取tagArray中标签的id。

    4.将postId和tagId分配给posttag(连接表),然后存入数据库。

    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();
    }
    

    【讨论】:

      【解决方案2】:

      您需要遍历新创建的标签并手动创建一个JournalEntryTags 对象,并为其提供对适当JournalEntryTag 对象的引用。

      然后您只需将其添加到数据库上下文中的集合中并保存更改。

      我还建议在实现这一点时考虑到编辑:您应该首先获取当前条目和各种标签之间的现有关系,删除新标签列表中不存在的那些,然后创建尚不存在的那些。

      【讨论】:

        猜你喜欢
        • 2020-11-16
        • 1970-01-01
        • 1970-01-01
        • 2011-12-22
        • 2020-11-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-28
        相关资源
        最近更新 更多