Adding Item with Many-to-Many Relationship In Entity Framework

后端 未结 2 1945
栀梦
栀梦 2020-12-10 15:11

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-t

相关标签:
2条回答
  • 2020-12-10 16:01

    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();
    }
    
    0 讨论(0)
  • 2020-12-10 16:17

    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/

    0 讨论(0)
提交回复
热议问题