LINQ to SQL 外键约束冲突

发布于 2024-09-01 06:13:10 字数 777 浏览 1 评论 0原文

我在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

A君 2024-09-08 06:13:10

创建关系并不意味着您必须加载组的事件 - 您仍然可以照常查询组。

Creating a relationship doesn't mean you have to load the Events for the Groups - you can still query the Groups as normal.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文