LINQ to SQL 外键约束冲突
我在使用 LINQ 时遇到问题。
我有 2 个表(父子关系)
Table1: Events (EventID, Description)
Table2: Groups (GroupID, EventID(FK), Description)
现在我想创建一个事件和一个子项。
Event e = new Event();
e.Description = "test";
Datacontext.Events.InsertOnSubmit(event)
Group g = new Group();
g.Description = "test2";
g.EventID = e.EventID;
Datacontext.Groups.InsertOnSubmit(g);
Datacontext.SubmitChanges();
当我调试时,我可以在插入事件后看到这一点。 EventID 已获得新值(自动递增)。
但是当 Datacontext.SubmitChanges();被叫。我收到以下异常,
"The INSERT statement conflicted with the FOREIGN KEY constraint ...
我知道这可以通过在事件和组之间的 LINQ 图中创建关系来解决。然后设置实体本身。但我不想每次询问组列表时都加载事件。
我需要的只是某种方式,当插入组失败时,事件插入不会在数据库中提交。
抱歉,如果这有点不清楚,我的英语不太好。
I'm having a problem with LINQ.
I have 2 tables (Parent-child relation)
Table1: Events (EventID, Description)
Table2: Groups (GroupID, EventID(FK), Description)
Now i want to create an Event an and a child.
Event e = new Event();
e.Description = "test";
Datacontext.Events.InsertOnSubmit(event)
Group g = new Group();
g.Description = "test2";
g.EventID = e.EventID;
Datacontext.Groups.InsertOnSubmit(g);
Datacontext.SubmitChanges();
When i debug, i can see that after inserting the event. the EventID has gotten a new value (auto increment).
But when Datacontext.SubmitChanges(); gets called. I get the following exception
"The INSERT statement conflicted with the FOREIGN KEY constraint ...
I know this can be solved by creating a relation in the LINQ diagram between Events and groups. And then setting the entity itself. But i don't want to load the events every time i ask a list of groups.
All i need is some way that when inserting the group fails, the event insert won't be committed in the database.
Sorry if this is a bit unclear, My English isn't really good.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
创建关系并不意味着您必须加载组的事件 - 您仍然可以照常查询组。
Creating a relationship doesn't mean you have to load the Events for the Groups - you can still query the Groups as normal.