与实体框架的多对多(单向)关系

时间:2012-09-25 16:41:32

标签: entity-framework entity-framework-4.1 ef-code-first

我正在使用Entity Framework 4.1和MVC 3.

我得到的问题是,当我将附带类别的新问题保存到数据库时,它应该只更新Question和QuestionCategories表,但是它会在Category表中添加一个新的重复条目。

public class Question{
   public int QuestionId{ get; set; }
   public string QuestionName { get; set;}
   public virtual IList<Category> Categories{ get; set; }
}

public class Category{
  public int CategoryId{ get; set; }
  public string CategoryName { get; set; }
}


modelBuilder.Entity<Question>()
   .HasMany(e => e.Categories)
   .WithMany() // don't need?
   .Map(mc => mc
   .ToTable("QuestionCategories")
   .MapLeftKey("QuestionId")
   .MapRightKey("CategoryId"));


public long CreateQuestion(Question question)
{ 
   this.repository.questions.Add(question); 
   this.repository.SaveChanges();
   return question.Id;

}


public void AddCategoryToQuestion(question question, List<long> CategoryIds)
{
   if (question.Categories == null)
       question.Categories = new List<Category>();

   foreach (long CategoryId in CategoryIds)
   {
       if (question.Categories.FirstOrDefault(q => q.Id == CategoryId) == null)
       {
           Category category = this.CategoryService.GetCategoryById(CategoryId);
           if (category != null)
           {
              question.Categories.Add(category);
           }
        }
   }
}

public void SaveQuestion(Question Question)
{
    this.repository.Questions.Attach(Question);
    this.repository.SetModified(Question);
    this.repository.SaveChanges();
}


Category Table 
Before SaveQuestion runs when user assigns Operations Category to a new question.

CategoryId  CategoryName 
1           Operations
2           Safety


After SaveQuestion runs

CategoryId  CategoryName 
1           Operations
2           Safety
3           Operations

提前谢谢。

0 个答案:

没有答案