如何避免在EF Core中插入具有相关实体的对象的多个数据库调用

时间:2019-09-25 03:54:46

标签: c# entity-framework-core ef-core-2.0 ef-core-2.1 ef-core-2.2

我有一张桌子说,交易有两个外键。一个外键引用客户表,另一个外键引用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次调用:

  1. 要获取与Customer对象中存在的ID对应的Transaction记录
  2. 要获取与BillAmount对象中存在的ID对应的Transaction记录
  3. INSERT命令最终插入一个新的Transaction对象

如何防止电话1)和2)?

1 个答案:

答案 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();
    }