2014-11-21 44 views
1

上下文類 這是我的上下文類。它的工作原理是在BlogsPostTags表中添加標籤的ID和標籤的ID ......但是它增加了新的標籤ID,而不是已經存儲在數據庫中的標籤。EF添加新的多對多記錄到表

public class WebsiteDBContext : DbContext 
{ 
    public DbSet<BlogPost> BlogPosts { get; set; } 
    public DbSet<Tag> Tags { get; set; } 
    public DbSet<Author> Authors { get; set; } 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<BlogPost>().HasRequired(bp => bp.Author).WithMany(a => a.BlogPosts); 
     base.OnModelCreating(modelBuilder); 

     modelBuilder.Entity<BlogPost>().HasMany(bp => bp.Tags).WithMany(t => t.Posts).Map(m => 
     { 
      m.MapLeftKey("BlogPostID"); 
      m.MapRightKey("TagID"); 
      m.ToTable("BlogPostTags"); 
     }); 
    } 
} 

我希望發生什麼:

Tag Table       BlogPostTags Table 

ID Name       BlogID TagID 
----------------     ---------------- 
1 Dogs       1   1 
2 Cats       1   9 
3 Birds       1   11 
4 Horses 
5 Rabbits 
6 Reptiles 
7 Insects 
8 Nature 
9 Puppies 
10 Kittens 
11 Cute 
12 Products 

但真正發生的事情是,它創建了標識爲標籤表的新標籤。像這樣

Tag Table       BlogPostTags Table 

ID Name       BlogID TagID 
----------------     ---------------- 
1 Dogs       1   13 
2 Cats       1   14 
3 Birds       1   15 
4 Horses 
5 Rabbits 
6 Reptiles 
7 Insects 
8 Nature 
9 Puppies 
10 Kittens 
11 Cute 
12 Products 
13 Dogs 
14 Puppies 
15 Cute 

Ov明顯重複名稱不好!我如何解決這個問題,以便獲得預期的結果?我的繼承人的ActionResult方法

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Create([Bind(Include = "Title,PublishDate,PublishTime,Body,AuthorID,Tags")] CreateBlogPostVM blogpost) 
{ 
    List<Tag> tags = new List<Tag>(); 
    foreach (var tag in blogpost.Tags.Where(t => t.IsChecked == true)) 
    { 
     tags.Add(new Tag { TagID = tag.TagID, Name = tag.Name }); 
    } 
    if (ModelState.IsValid) 
    { 
     BlogPost newPost = new BlogPost 
     { 
      Title = blogpost.Title, 
      PublishDate = blogpost.PublishDate, 
      PublishTime = blogpost.PublishTime, 
      Body = blogpost.Body, 
      Author = db.Authors.Where(bp => bp.AuthorID == blogpost.AuthorID).Single(), 
      Tags = tags //Add list of tags 
     }; 
     db.BlogPosts.Add(newPost); 
     db.SaveChanges(); 
     return RedirectToAction("Index"); 
    } 

    return View(blogpost); 
} 

回答

1

你需要找到一個已經在你的數據庫,而不是增加新的存在現有的標籤。替換此:

 foreach (var tag in blogpost.Tags.Where(t => t.IsChecked == true)) 
     { 
      tags.Add(new Tag { TagID = tag.TagID, Name = tag.Name }); 
     } 

有:

 foreach (var tag in blogpost.Tags.Where(t => t.IsChecked == true)) 
     { 
      tags.Add(db.Tags.Find(tag.TagID)); 
     } 

(假設標籤識別是你的標籤表的主鍵,如果不是你可以這樣做tags.Add(db.Tags.Where(t=>t.TagID == tag.TagID).First())

+0

完美的作品,我沒」不要太確定正確的做法。謝謝 – Ultigma 2014-11-21 22:52:48