2

我将 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

先感谢您。

4

0 回答 0