我正在尝试将盒子从一个用户转移到另一个(并记录转移)。但是,当我运行数据库“添加”方法时,当我需要保持原样的FK传递给我的Transfer类时,它们的框号会增加(当然,TransferID将在添加时递增,这是我所需要的)。我有两个类/表:
转移:
public class Transfer
{
public int TransferID { get; set; }
public string SentBy { get; set; }
public string SentByDisplayName { get; set; }
public string ReceivedBy { get; set; }
public string ReceivedByDisplayName { get; set; }
public virtual List<Box> Boxes { get; set; }
}
此Transfer类与Boxes
具有一对多连接,该连接具有以下属性:
public class Box
{
//PKey
public int ID { get; set; }
public string BoxID { get; set; }
//FKey
public string StorageRequestID { get; set; }
//FKey
public int? TransferID { get; set; }
public string RecordsCustodian { get; set; }
public virtual Transfer Transfer { get; set; }
/////Tons of properties removed for brevity
}
对于传输,我需要更新 Box对象的RecordsCustodian
(和其他一些属性),并将更改记录到Transfer
表中。
public void TransferBoxes(Transfer data)
{
//Create LDAP user that will receive the transfer request
LDAPUser transferReceiver = PriUtil.GetUser(data.ReceivedBy);
//Create LDAP user that sent the transfer request
LDAPUser transferSender = PriUtil.GetUser(data.SentBy);
//Create the transfer row identifying the sender and receiver
//to display on transfer history page
data.SentBy = transferSender.JplUsername;
data.SentByDisplayName = transferSender.DisplayName;
data.ReceivedBy = transferReceiver.JplUsername;
data.ReceivedByDisplayName = transferReceiver.DisplayName;
db.Transfers.Add(data);
db.SaveChanges();
//Transfer Ownership
foreach (Box singleBox in data.Boxes)
{
singleBox.RecordsCustodian = transferReceiver.JplUsername;
singleBox.RecordsCustodianDisplay = transferReceiver.DisplayName;
singleBox.BoxDescription = singleBox.BoxDescription + Environment.NewLine + "---- Transfer Notes on " + DateTime.Now + " ----" + Environment.NewLine + data.TransferDescription;
singleBox.TransferID = data.TransferID;
db.Boxes.Attach(singleBox);
db.Entry(singleBox).State = EntityState.Modified;
}
db.SaveChanges();
}
但是,当我运行
db.Transfers.Add(data);
db.SaveChanges();
(其中包含框列表),这些框的主键ID都增加了,因此当我更新foreach
循环中的框并attach
进行更新时,它们不会不再包含其原始ID,因此他们没有更新,而是在我的数据库中创建了新行...
所以我的问题是,如何在不影响框列表的主键的情况下添加转移行(创建在foreach循环中需要使用的TransferID)?
谢谢