添加项目有很多一对多的关系在实体框架有很多、实体、框架、关系

2023-09-03 00:57:24 作者:好听的没人用的 好听不俗气小众

我收到一个主键冲突错误,当我尝试添加一个项目有许多一对多的关系:

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
            }

        }

此功能基本上将检查是否有在数据库中可用的标记,如果是这样返回标记,然后加入到第对象的使用article.Tags.Add标签集合()。

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().

然而,当我尝试这种使用下面的code,我收到了违反PRIMARY KEY约束错误保存

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.

推荐答案

使用相同的上下文实例为您的操作的整个加工和你的生活会更容易:

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