【问题标题】:UWP and SQLite: How to work with Many-to-Many relationshipUWP 和 SQLite:如何处理多对多关系
【发布时间】:2017-07-12 13:00:24
【问题描述】:

我正在关注this,我的问题是: 如果 Post 和 Tag 表之间存在连接表,那么每当我想向 Post 添加标签列表时,我应该使用 Post 和 Tag 类中的 PostTags 属性吗?这是正确的做法吗?

这是我正在谈论的代码:

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public List<PostTag> PostTags { get; set; }
}

public class Tag
{
    public string TagId { get; set; }

    public List<PostTag> PostTags { get; set; }
}

public class PostTag
{
    public int PostId { get; set; }
    public Post Post { get; set; }

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

【问题讨论】:

    标签: .net database entity-framework sqlite uwp


    【解决方案1】:

    每当我想向帖子添加标签列表时,我应该使用 Post 和 Tag 类中的 PostTags 属性?

    如果您使用above document 中的多对多关系部分的示例代码,答案是。您应该能够使用Post 实体的PostTags 属性将记录添加到PostTag 表中。

    如果您想将Tags 列表添加到Post 以及Post 是新创建的,您可以使用以下代码:

    using (var db = new MyContext())
    {
        var posttag = new PostTag { TagId = txttagjoinId.Text };
        Post newone = new Post()
        {
            Content = "new content",
            Title = "new title"
        };
        newone.PostTags = new List<PostTag>() { posttag };      
        db.Posts.Add(newone);                
        db.SaveChanges();
    }
    

    如果您想将Tags 列表添加到已存在的Post 中,您可以先获取该帖子,然后为其更新PostTags 属性。以下代码将Tags 列表添加到第一个Post 记录:

    using (var db = new MyContext())
    {
        var posttag = new PostTag { TagId = txttagjoinId.Text };
        List<Post> allposts = db.Posts.ToList();
        allposts[0].PostTags = new List<PostTag>() { posttag };
        db.Posts.Update(allposts[0]);
        db.SaveChanges();
    }
    

    如果您将public DbSet&lt;PostTag&gt; PostTags { get; set; } 添加到MyContext 类,您可能不需要PostTags 属性,您应该可以将记录添加到PostTag 表,如下所示,但可能不推荐这样做:

    using (var db = new MyContext())
    {
       var posttag = new PostTag { TagId = txttagjoinId.Text, PostId = 1 };
       db.PostTags.Add(posttag);
       db.SaveChanges();
    }
    

    注意表PostTags是用外键PostIdTagId创建的,当你添加或更新记录时,你需要满足约束。

    【讨论】:

      猜你喜欢
      • 2016-10-04
      • 1970-01-01
      • 1970-01-01
      • 2018-02-17
      • 2021-01-28
      • 2022-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多