简体   繁体   English

C#设置外键

[英]C# setting foreign key

I have a form to input data of an Owner and a Pet into a database. 我有一种表单,可以将所有者和宠物的数据输入数据库。 The pet has a foreign key of the owner id, the data of the Owner and the Pet are filled in the same form, so how do I set the owner id in the pet object if the ownerID has not been set in the database yet? 宠物具有所有者ID的外键,所有者和宠物的数据填写在同一表格中,因此,如果尚未在数据库中设置ownerID ,如何在宠物对象中设置所有者ID? Or just I have to set the owner in the database first? 或者只是我必须先在数据库中设置所有者?

Class Owner attributes Owner属性

private int32 idOwner;
private String name;

Class Pet attributes; Pet属性;

private int32 Pet;
private int32 idOwner;    // foreign key
private String name;

Form 形成

Owner owner = new Owner();
owner.Name = this.ownerNameTxt.Text.Trim();
OwnerService.addOwner(owner); // add owner to database

Pet pet = new Pet();
pet.name = this.petNameTxt.Text.Trim();
pet.idOwner = ????????

So you have an identity column idOwner which gets generated on insert and you want to set that id in the Pet object. 因此,您具有一个标识列idOwner ,该列在插入时生成,并且您想要在Pet对象中设置该ID。 Then you need to modify your OwnerService.addOwner method in order to select the generated ID from the database and update the owner object. 然后,您需要修改OwnerService.addOwner方法,以便从数据库中选择生成的ID并更新所有者对象。

private void addOwner(owner)
{
    // your current logic here but modify to
    // add  ;SELECT  SCOPE_IDENTITY(); at the end of your insert query.
    // and store it in a local int. eg int ownerID = (int)cmd.ExecuteScalar();

    owner.idOwner = ownerID;
}

Then your form code: 然后您的表单代码:

Owner owner = new Owner();
owner.Name = this.ownerNameTxt.Text.Trim();
OwnerService.addOwner(owner); // add owner to database

Pet pet = new Pet();
pet.name = this.petNameTxt.Text.Trim();
pet.idOwner = owner.idOwner;

Docs for SCOPE_IDENTITY (Transact-SQL) : 适用于SCOPE_IDENTITY的文档(Transact-SQL)

Returns the last identity value inserted into an identity column in the same scope. 返回插入到同一作用域的标识列中的最后一个标识值。 A scope is a module: a stored procedure, trigger, function, or batch. 范围是一个模块:存储过程,触发器,函数或批处理。 Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch. 因此,如果两个语句位于相同的存储过程,函数或批处理中,则它们属于同一范围。

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

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