我有一个表单,用于将所有者和宠物的数据输入到数据库中。宠物具有所有者ID的外键,所有者和宠物的数据以相同的形式填充,因此如果尚未设置Owner
,如何在宠物对象中设置所有者ID数据库了吗?或者我必须首先在数据库中设置所有者?
类private int32 idOwner;
private String name;
属性
Pet
类private int32 Pet;
private int32 idOwner; // foreign key
private String name;
属性;
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 = ????????
表格
XmlNode n = (XmlNode)((VirtualNode)node.Unwrap()).getUnderlyingXmlNode();
IXmlInfo xInfo = (IXmlInfo)n;
int line = xInfo.LineNumber;
int col = xInfo.LinePosition;
答案 0 :(得分:1)
因此,您有一个标识列idOwner
,它会在插入时生成,您希望在Pet
对象中设置该标识。然后,您需要修改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;
}
然后是您的表单代码:
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;
SCOPE_IDENTITY (Transact-SQL)的文档:
返回插入标识列的最后一个标识值 相同的范围。范围是一个模块:存储过程,触发器, 功能或批处理。因此,如果两个语句属于同一范围 它们处于相同的存储过程,功能或批处理中。