我对实体框架颇为陌生,因此我可能忽略了一些简单的东西。实体框架:将实体A链接到现有实体B
在我的控制器类中,我将一个新的Category实体添加到数据库,接下来我将该实体用作Course实体的一个属性。当我保存课程实体时,该类别再次保存到数据库,而我希望新课程将引用已插入的类别。
,节省了第一类(简体)控制器代码:
// Create and save the category
Category category = new Category {Name = "Test category"};
category = context.Categories.Add(category);
context.SaveChanges(); // The category object now has a CategoryId (the pk of the record)
// Create and save the course
Course course = new Course {
FullDescription = "This is a new course",
Name = "My new course",
Category = category // Hoping this will have EF make a link to the just inserted category
};
context.Courses.Add(course);
context.SaveChanges(); // Saves the Course AND creates a **new** Category in the db
这个问题似乎是我的SaveChanges调用()的两倍。什么工作是删除第一个调用context.saveChanges(),但是,这不是我的实际代码。在我的应用程序中,我使用存储库模式,并通过调用categoryRepository.AddCategory(Category category)来添加类别。保存课程的方式完全相同,只需调用courseRepo.AddCourse(课程课程),其中也包含对saveChanges()的调用。
public Category AddCategory(Category category)
{
category = context.Categories.Add(category);
context.SaveChanges();
return category;
}
我不想删除对的SaveChanges()调用在AddCourse()和AddCategory(),因为我想这些是原子操作。
我曾希望返回类别并随后将该类别用作新课程的属性会将该课程链接到该类别,但显然情况并非如此。如何将我的课程链接到数据库中已存在的类别?
您在存储库中使用单独的上下文实例,对不对?否则,你的代码会真正起作用。 – Slauma 2012-03-31 15:29:59