简体   繁体   English

使用C#将外键插入表中

[英]Inserting a Foreign Key into a table using C#

I hope you don't mind if I ask for your opinions about how to insert a foreign key into a table without running a couple of queries. 希望您不要介意我是否希望您在不运行几个查询的情况下将外键插入表中。

I have made a sample UI and a sample table just to illustrate my situation. 我制作了一个示例UI和一个示例表来说明我的情况。

在此处输入图片说明

Here's what I usually do when inserting, first I do a query against the database and loads the result into the ComboBox. 这是插入时通常执行的操作,首先,我对数据库进行查询并将结果加载到ComboBox中。 After that I run a query again to get the Id of the selectedItem on the comboBox before doing the INSERT or UPDATE query, but it feels like there is a much better solution without hitting the database too much. 之后,我再次运行查询以在执行INSERT或UPDATE查询之前在comboBox上获取selectedItem的ID,但是感觉有一个更好的解决方案,而又不会对数据库造成太大的麻烦。

Any idea will be greatly appreciated. 任何想法将不胜感激。

Regards. 问候。

When loading the items into the ComboBox you could use a dataset, say like retrieved from this 将项目加载到ComboBox您可以使用数据集,例如从此检索

"SELECT Id, NameColumn FROM sampleTable"

Then you can set the ComboBox DisplayMember and ValueMember attributes like so 然后,您可以像这样设置ComboBox DisplayMemberValueMember属性

combobox1.ValueMember = "Id";
combobox1.DisplayMember = "NameColumn";

That way, when you try to retrieve the Id of the item all you need to do is something like 这样,当您尝试检索该项目的Id ,您要做的只是

var item = combobox1.SelectedValue;

You only need to hit the database now to load the items into the ComboBox in the first place, before your INSERT or UPDATE . 您只需要立即访问数据库,即可在INSERTUPDATE之前首先将项目加载到ComboBox中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM