2012-06-27 92 views
0

我在實體框架中有多對多的關係。請查看圖片... many to many


我想插入此項目的項目和標籤, TagName屬性是分貝唯一的,因此我需要在Tags插入並在ArticlesToTags只有新標籤(不可見在EF)表中,而其他已經在Tags中的其他字段只需要插入ArticlesToTagsEF中插入多對多邏輯

public void CreateUpdate(string title, string subTitle, string text, 
       string author, string tags, string photo, bool allowComments) 
      { 
       using (var context = new blogEntities()) 
       { 
         var article = new Article() 
         { 
          Title = title, 
          SubTitle = subTitle, 
          ArticleText = text, 
          Author = author, 
          Photo = photo, 
          CreateDate = DateTime.Now, 
          ModifyDate = null, 
          AllowComments = allowComments 
         }; 

         foreach (var tg in tags.Split(',')) 
         { 
          article.Tags.Add(new Tag() { TagName = tg }); 
         } 

         context.Articles.AddObject(article); 

        context.SaveChanges(); 
       } 
      } 



現在拋出重複的唯一鍵的例外不能插入它是如何在EF做了什麼?我是新手...

回答

3

添加一條select語句來查看數據庫中是否已經有一個標籤。

foreach (var tg in tags.Split(',')) 
{ 
    var tag = context.Tags.SingleOrDefault(x => x.TagName == tg); 
    if (tag == null) 
     tag = new Tag() { TagName = tg }; 

    article.Tags.Add(tag); 
} 
0

檢查您的數據庫,您必須添加一個雙列主鍵到您的關係表。 這樣的: enter image description here

這裏是我的代碼,同樣對你的,它的工作原理:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace ConsoleApplication13 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      using (manytomanyEntities entities = new manytomanyEntities()) 
      { 
       List<B> bList = new List<B>(); 

       A a = new A 
       { 
        Name = "Tim_A" 
       }; 

       for (int i = 0; i < 100; i++) 
       { 
        B b = new B 
        { 
         Name = "Tim_B_" + i 
        }; 

        entities.B.AddObject(b); 
       } 

       entities.A.AddObject(a); 

       entities.SaveChanges(); 

      } 
     } 
    } 
} 

希望這可以幫助您,:)