我正在使用EF4和它的新功能。我的项目中有很多很多,似乎无法弄清楚如何插入或更新。我建立了一个小项目,只是为了看看应该如何编码。
假设我有3张桌子
添加所有关系并通过模型浏览器更新模型后,我注意到没有出现StudentClass,这似乎是默认行为。
现在,我需要同时进行插入和更新。你怎么做呢?我可以下载示例的任何代码示例或链接,还是可以节省5分钟?
最佳答案
就实体(或对象)而言,您有一个Class
对象,该对象具有Students
的集合;一个Student
对象,其具有Classes
的集合。由于您的StudentClass
表仅包含ID,并且没有其他信息,因此EF不会为联接表生成实体。这是正确的行为,这就是您所期望的。
现在,在进行插入或更新时,请尝试根据对象进行思考。例如。如果要插入一个有两个学生的类(class),请创建Class
对象,Student
对象,将学生添加到类(class)Students
集合中,然后将Class
对象添加到上下文中,然后调用SaveChanges
:
using (var context = new YourContext())
{
var mathClass = new Class { Name = "Math" };
mathClass.Students.Add(new Student { Name = "Alice" });
mathClass.Students.Add(new Student { Name = "Bob" });
context.AddToClasses(mathClass);
context.SaveChanges();
}
这将在
Class
表中创建一个条目,在Student
表中创建两个条目,并在StudentClass
表中创建两个条目将它们链接在一起。基本上,您需要进行相同的更新。只需获取数据,通过在集合中添加和删除对象来修改图形,然后调用
SaveChanges
即可。有关详细信息,请检查this similar question。编辑:
根据您的评论,您需要插入一个新的
Class
并向其中添加两个现有的Students
:using (var context = new YourContext())
{
var mathClass= new Class { Name = "Math" };
Student student1 = context.Students.FirstOrDefault(s => s.Name == "Alice");
Student student2 = context.Students.FirstOrDefault(s => s.Name == "Bob");
mathClass.Students.Add(student1);
mathClass.Students.Add(student2);
context.AddToClasses(mathClass);
context.SaveChanges();
}
由于两个学生都已经在数据库中,因此不会插入他们,但是由于他们现在都在
Students
的Class
集合中,因此会将两个条目插入StudentClass
表中。关于c# - 插入/更新多对多 Entity Framework 。我该怎么做?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4253165/