Entity framework 实体框架:将实体A链接到现有实体B

Entity framework 实体框架:将实体A链接到现有实体B,entity-framework,entity-framework-4.1,Entity Framework,Entity Framework 4.1,我对实体框架相当陌生,所以我可能忽略了一些简单的东西 在我的控制器类中,我将向数据库添加一个新的类别实体,接下来我将该实体用作课程实体的属性。当我保存课程实体时,类别将再次保存到数据库中,而我希望新课程将引用已插入的类别 保存第一个类别的(简化)控制器代码: // Create and save the category Category category = new Category {Name = "Test category"}; category = context.Categories

我对实体框架相当陌生,所以我可能忽略了一些简单的东西

在我的控制器类中,我将向数据库添加一个新的类别实体,接下来我将该实体用作课程实体的属性。当我保存课程实体时,类别将再次保存到数据库中,而我希望新课程将引用已插入的类别

保存第一个类别的(简化)控制器代码:

// 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()的调用

我不想删除AddCourse()和AddCategory()中对saveChanges()的调用,因为我希望这些是原子操作


我希望返回该类别,然后将该类别用作新课程的属性,可以将该课程与该类别联系起来,但显然情况并非如此。如何将课程链接到数据库中已存在的类别?

我不确定数据模型的结构,但您可以这样做

course.CategoryId = category.CategoryId;
通过这种方式,您可以映射关系中的实际外键,它也会执行相同的操作

Category category = new Category {Name = "Test category"};
Course course = new Course {
FullDescription = "This is a new course",
  Name = "My new course",
  Category =  category 
};

courseRepo.AddCourse(course);

如果您的存储库具有相同的上下文,则只能使用AddCourse来添加这两个实体。如果每个存储库都有自己的上下文,您应该将类别附加到courseRepo上下文或将实体加载到其中(但我认为它不适合您,因为您有不同的存储库)。

您在存储库中使用的是单独的上下文实例,对吗?否则,你的代码实际上会起作用。我解决了这个问题,没有在课程上设置类别,只设置CategoryId。这与我的直觉背道而驰,因为在Hibernate(可能还有NHibernate?)中,当您在这样的课程上设置一个类别时,假设您希望将课程链接到该现有类别。但也许这就是EF的工作原理!谢谢
Category category = new Category {Name = "Test category"};
Course course = new Course {
FullDescription = "This is a new course",
  Name = "My new course",
  Category =  category 
};

courseRepo.AddCourse(course);