WCF 数据服务:将两个新对象添加到数据库中,并在它们之间建立链接
我的数据库中有这两个表:
班级 (*)<---------(1) 教师 -------- --------
一个老师有多个班级,而一个班级只属于一个老师。
我在 wcf 数据服务客户端中执行此操作:
var teacher = new Teacher(1, "John");
var class1 = new Class
{
teacherId=teacher1.Id,
teacher=teacher1
};
teacher1.Classes.Add(class1);
service.AddObject("Classes", class1);
service.AddObject("Teachers", teacher1);
service.AddLink(teacher1, "Classes", class1);
service.SetLink(class1, "Teacher", teacher);
service.SaveChanges();
执行时出现以下异常:
“INSERT 语句与 FOREIGN KEY 约束 \"Teachers_Classes\" 发生冲突。冲突发生在数据库 \"MyDatabase\"、表 \"dbo.Teachers\"、列 'TeacherId' 中。\r\n该语句有已被终止。”
这是表 Classes 中定义的约束:
ALTER TABLE [dbo].[Classes] WITH CHECK ADD CONSTRAINT
[Teachers_Classes] FOREIGN KEY([Teachers_TeacherId])
REFERENCES [dbo].[Teachers] ([TeacherID])
GO
I have these two tables in my database :
classes (*)<----------(1) teachers
------- --------
a teacher has many classes while a class only belongs to one teacher.
I do this in my wcf data services client :
var teacher = new Teacher(1, "John");
var class1 = new Class
{
teacherId=teacher1.Id,
teacher=teacher1
};
teacher1.Classes.Add(class1);
service.AddObject("Classes", class1);
service.AddObject("Teachers", teacher1);
service.AddLink(teacher1, "Classes", class1);
service.SetLink(class1, "Teacher", teacher);
service.SaveChanges();
I get the following exception when I execute :
"The INSERT statement conflicted with the FOREIGN KEY constraint \"Teachers_Classes\". The conflict occurred in database \"MyDatabase\", table \"dbo.Teachers\", column 'TeacherId'.\r\nThe statement has been terminated."
Here is the Constraint defined in the table Classes :
ALTER TABLE [dbo].[Classes] WITH CHECK ADD CONSTRAINT
[Teachers_Classes] FOREIGN KEY([Teachers_TeacherId])
REFERENCES [dbo].[Teachers] ([TeacherID])
GO
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我找到了解决方案:
我必须将 SaveChangesOption 传递给 service.SaveChanges() 方法:
I found the solution :
I had to pass in SaveChangesOption to the service.SaveChanges() method :