简体   繁体   中英

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? Or just I have to set the owner in the database first?

Class Owner attributes

private int32 idOwner;
private String name;

Class Pet attributes;

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. Then you need to modify your OwnerService.addOwner method in order to select the generated ID from the database and update the owner object.

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) :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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