在实体框架中添加具有多对多关系的项目

发布于 2024-11-26 03:28:22 字数 1270 浏览 3 评论 0 原文

当我尝试添加具有多对多关系的项目时,出现主键冲突错误:

我有两个类 - 具有多对多关系的文章和标签:

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

public class Tag
{ 
    [Key]
    public string UrlSlug { get; set; }
    public string Name { get; set; }
    public ICollection<Article> Articles{ get; set; }
}

当我添加新文章时,我允许用户输入任何标签,然后如果数据库中尚未创建标签,我想创建一个新标签,或者如果标签已存在,则将标签添加到 Article 对象的 Tags 集合中。

因此,当我创建新的 Article 对象时,我调用以下函数:

public static Tag GetOrLoadTag(String tagStr)
{
    string tagUrl = Tag.CreateTagUrl(tagStr);
    var db = new SnippetContext();
    var tagFromDb = from tagdummy in db.Tags.Include(x => x.Articles)
                    where tagdummy.UrlSlug == tagUrl
                    select tagdummy;
    if (tagFromDb.FirstOrDefault() != null)
    { return tagFromDb.FirstOrDefault(); }
    else
    {
        //create and send back a new Tag
    }
}

该函数主要检查数据库中是否有可用的 Tag,如果有则返回该 Tag,然后使用article.Tags 将其添加到 Article 对象的 Tag 集合中。添加()。

但是,当我尝试使用下面的代码保存它时,我收到违反主键约束错误,

 db.Entry(article).State = EntityState.Modified;
 db.SaveChanges();

我不知道应该如何在文章和现有标签之间创建关系。

I am getting a primary key violation error when I attempt to add an item with a many-to-many relationship:

I have two classes - Articles and Tags which have a many-to-many relationship :

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

public class Tag
{ 
    [Key]
    public string UrlSlug { get; set; }
    public string Name { get; set; }
    public ICollection<Article> Articles{ get; set; }
}

When I add a new Article I allow the user to input any Tags and then I want to create a new Tag if the Tag isn't created yet in the database or add the Tag to the Tags collection of the Article object if the Tag already exists.

Therefore when I am creating the new Article object I call the below function:

public static Tag GetOrLoadTag(String tagStr)
{
    string tagUrl = Tag.CreateTagUrl(tagStr);
    var db = new SnippetContext();
    var tagFromDb = from tagdummy in db.Tags.Include(x => x.Articles)
                    where tagdummy.UrlSlug == tagUrl
                    select tagdummy;
    if (tagFromDb.FirstOrDefault() != null)
    { return tagFromDb.FirstOrDefault(); }
    else
    {
        //create and send back a new Tag
    }
}

This function basically checks if there is an available Tag in the database and if so returns that Tag which is then added to the Tag collection of the Article object using article.Tags.Add().

However, when I attempt to save this using the below code I get a Violation of PRIMARY KEY constraint error

 db.Entry(article).State = EntityState.Modified;
 db.SaveChanges();

I can't figure out how I should go about just creating a relationship between the Article and the already existing Tag.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

雪若未夕 2024-12-03 03:28:22

在整个操作过程中使用相同的上下文实例,您的生活会变得更加轻松:

using (var ctx = new MyContext())
{
    Article article = ctx.Articles.Single(a => a.Id == articleId);
    Tag tag = ctx.Tags.SingleOrDefault(t => t.UrlSlug == tagUrl);
    if (tag == null) 
    {
       tag = new Tag() { ... }
       ctx.Tags.AddObject(tag);
    }

    article.Tags.Add(tag);
    ctx.SaveChanges();
}

如果您不想从数据库加载文章(如果您知道该文章存在,则该查询是多余的),您可以使用:

using (var ctx = new MyContext())
{
    Article article = new Article() { Id = articleId };
    ctx.Articles.Attach(article);

    Tag tag = ctx.Tags.SingleOrDefalut(t => t.UrlSlug == tagUrl);
    if (tag == null) 
    {
       tag = new Tag() { ... }
       ctx.Tags.AddObject(tag);
    }

    article.Tags.Add(tag);
    ctx.SaveChanges();
}

Use the same context instance for the whole processing of your operation and your life will be much easier:

using (var ctx = new MyContext())
{
    Article article = ctx.Articles.Single(a => a.Id == articleId);
    Tag tag = ctx.Tags.SingleOrDefault(t => t.UrlSlug == tagUrl);
    if (tag == null) 
    {
       tag = new Tag() { ... }
       ctx.Tags.AddObject(tag);
    }

    article.Tags.Add(tag);
    ctx.SaveChanges();
}

If you don't want to load the article from database (that query is redundant if you know that article exists) you can use:

using (var ctx = new MyContext())
{
    Article article = new Article() { Id = articleId };
    ctx.Articles.Attach(article);

    Tag tag = ctx.Tags.SingleOrDefalut(t => t.UrlSlug == tagUrl);
    if (tag == null) 
    {
       tag = new Tag() { ... }
       ctx.Tags.AddObject(tag);
    }

    article.Tags.Add(tag);
    ctx.SaveChanges();
}
定格我的天空 2024-12-03 03:28:22

您如何创建新标签?以及如何将现有或创建的实体附加到文章中。

使用类似

Article a = new Article(...);
a.tags.add(GetOrLoadTag("some tag"));

阅读这篇文章http://thedatafarm.com/blog/data-access/inserting-many-to-many-relationships-in-ef-with-or-without-a-join-entity/

How do you go about creating new tags? And how do you attach the existing or created entity to the the article.

Use something like

Article a = new Article(...);
a.tags.add(GetOrLoadTag("some tag"));

Read this article http://thedatafarm.com/blog/data-access/inserting-many-to-many-relationships-in-ef-with-or-without-a-join-entity/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文