我正在向大约6家银行插入5000笔交易,但我在数据库中获得了5000个银行行,并且名称重复。
public class Transaction
{
[Key]
public int Id { get; set; }
public DateTime TransDate { get; set; }
public decimal Value { get; set; }
public string Description { get; set; }
public Bank Bank { get; set; }
}
public class Bank
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
public class FinancialRecordContext : DbContext
{
public FinancialRecordContext() : base("FinancialRecordDatabase") { }
public DbSet<Transaction> Transactions { get; set; }
public DbSet<Bank> Banks { get; set; }
public Bank FindOrInsertBank(string bankName)
{
var bank = Banks.SingleOrDefault(b => b.Name == bankName);
if (bank == null)
{
bank = new Bank { Name = bankName };
Banks.Add(bank);
}
return bank;
}
}
然后插入我循环浏览一些数据并插入:
using (var context = new FinancialRecordContext())
{
foreach (var t in data)
{
var tran = new Transaction
{
Description = t.Description,
Value = t.Value,
TransDate = t.TransDate,
Bank = context.FindOrInsertBank(t.BankName)
};
context.Transactions.Add(tran);
}
context.SaveChanges();
}
似乎FindOrInsertBank
方法一直进入数据库,而不是在本地查看最近添加的,但未提交的银行。我该怎么做/应该这样做?
每次银行插入后我应SaveChanges
吗?不是我想要做的事情,我希望这是一次交易。
答案 0 :(得分:2)
您可以尝试查询更改跟踪器(这是内存中查询,而不是数据库查询):
using (var context = new FinancialRecordContext())
{
foreach (var t in data)
{
Bank bank = context.ChangeTracker.Entries()
.Where(e => e.Entity is Bank && e.State != EntityState.Deleted)
.Select(e => e.Entity as Bank)
.SingleOrDefault(b => b.Name == t.BankName);
if (bank == null)
bank = context.FindOrInsertBank(t.BankName);
var tran = new Transaction
{
Description = t.Description,
Value = t.Value,
TransDate = t.TransDate,
Bank = bank
};
context.Transactions.Add(tran);
}
context.SaveChanges();
}
修改强>
在这里使用更改跟踪器可能对性能不利,因为Bank.Name
不是实体的关键,我想查询将是对条目的线性搜索。在这种情况下,使用手写字典可能是更好的解决方案:
using (var context = new FinancialRecordContext())
{
var dict = new Dictionary<string, Bank>();
foreach (var t in data)
{
Bank bank;
if (!dict.TryGetValue(t.BankName, out bank))
{
bank = context.FindOrInsertBank(t.BankName);
dict.Add(t.BankName, bank);
}
var tran = new Transaction
{
Description = t.Description,
Value = t.Value,
TransDate = t.TransDate,
Bank = bank
};
context.Transactions.Add(tran);
}
context.SaveChanges();
}
答案 1 :(得分:2)
尝试一些建议:
1)先检查Local
DbSet<Bank>
的{{1}}集合。
public Bank FindOrInsertBank(string bankName)
{
var bank = Banks.Local.SingleOrDefault(b => b.Name == bankName);
if (bank == null)
{
var bank = Banks.SingleOrDefault(b => b.Name == bankName);
if (bank == null)
{
bank = new Bank { Name = bankName };
Banks.Add(bank);
}
}
return bank;
}
2)每次更新后强制拨打DetectChanges()
context.Transactions.Add(tran);
context.ChangeTracker.DetectChanges();