我有一张桌子说,交易有两个外键。一个外键引用客户表,另一个外键引用BillAmount表。所以我的POCO就像
public class Transaction
{
public string Id { get; set; }
public string CustomerId { get; set; }
public string BillAmountId { get; set; }
}
public class Customer
{
public string Id {get;set;}
public string Name {get;set;}
}
public class BillAmount
{
public string Id {get;set;}
public double Amount {get;set;}
}
当我尝试插入新的Transaction
对象时,我注意到总共对数据库进行了3次调用:
Customer
对象中存在的ID对应的Transaction
记录BillAmount
对象中存在的ID对应的Transaction
记录INSERT
命令最终插入一个新的Transaction
对象如何防止电话1)和2)?
答案 0 :(得分:0)
首先,如果您使用ORM工具(如EF核心),则应根据它来重新组织实体;
public class Transaction {
public string Id { get; set; }
public Customer Customer { get; set; }
public BillAmount BillAmount { get; set; }
}
public class Customer {
public string Id { get; set; }
public string Name { get; set; }
}
public class BillAmount {
public string Id { get; set; }
public double Amount { get; set; }
}
当您按如下所示致电时,它会在一笔交易(一次插入)中完成您的工作。
public void InsertTransaction() {
//Some dummy data
Customer customer = new Customer();
customer.Id = "5";
customer.Name = "George";
BillAmount billAmount = new BillAmount();
billAmount.Id = "7";
billAmount.Amount = 2.0;
Transaction transaction = new Transaction();
transaction.Id = "1";
transaction.Customer = customer;
transaction.BillAmount = billAmount;
//Complete in one insert
context.Transaction.Add(transaction);
context.SaveChanges();
}