2012-03-31 113 views
1

我对实体框架颇为陌生,因此我可能忽略了一些简单的东西。实体框架:将实体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(),因为我想这些是原子操作。

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

+0

您在存储库中使用单独的上下文实例,对不对?否则,你的代码会真正起作用。 – Slauma 2012-03-31 15:29:59

回答

2

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

course.CategoryId = category.CategoryId; 

这样你映射关系中的实际外键,它做同样的事情。

+0

我解决了这个问题,没有在课程上设置Category,而只是CategoryId。这对我来说是违反直觉的,因为在Hibernate(也许是NHibernate?)中,当你在课程中设置一个CategoryId类别的类别时,假设你想将该课程链接到该现有类别。但也许这就是EF如何运作!谢谢。 – Julius 2012-04-01 10:25:22

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