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

时间:2012-03-31 14:44:04

标签: entity-framework entity-framework-4.1

我对实体框架很陌生,所以我可能会忽略一些简单的事情。

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

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

// 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(类别类别)来添加类别。通过调用courseRepo.AddCourse(课程课程),同时包含对saveChanges()的调用,保存课程的方式完全相同。

public Category AddCategory(Category category)
    {
        category = context.Categories.Add(category);
        context.SaveChanges();
        return category;
    }

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

我希望返回该类别,然后在新课程中使用该类别作为属性将该课程链接到该类别,但显然并非如此。如何将课程链接到数据库中已存在的类别?

2 个答案:

答案 0 :(得分:2)

我不确定您的数据模型是如何构建的,但您可以这样做。

course.CategoryId = category.CategoryId;

这样你就可以在关系中映射实际的外键,它也会做同样的事情。

答案 1 :(得分:0)

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上下文或将实体加载到其中(但我认为它不适合您,因为您有不同的存储库)。