我正在尝试保存到两个不同的表中。从Taxlaw中获取数据并保存时,我将相同数据保存在taxlawhistory表中。因此,就像将数据从一个表复制到另一表一样,这是行不通的。我不断收到的错误是
无法从Model.TaxLaw转换为Model.TaxTableHisory
public async Task<bool> SaveOrUpdate(IEnumerable<TaxLaw> obj)
{
using (var trans = _taxhistoryrepo.DbContext.Database.BeginTransaction())
{
var lists = new List<TaxTableHistory>();
foreach (var list in obj)
{
lists.CompanyCode = list.CompanyCode;
lists.CummulativeAmount = list.CummulativeAmount;
lists.Percentage = list.Percentage;
lists.ModifiedDate = DateTime.UtcNow;
lists.ModifiedDate = list.ModifiedDate;
lists.Status = EntityStatus.Active;
_taxhistoryrepo.DbSetEntity.Add(lists);
await _taxhistoryrepo.DbContext.SaveChangesAsync();
await Task.FromResult(_repository.SingleSave(obj));
}
trans.Commit();
}
return true;
}
最佳答案
obj是类型
IEnumerable<TaxLaw>
所以每个团队
TaxLaw
然后,您尝试保存到
_taxhistoryrepo
我相信正在使用
TaxHistory
这部分代码:
foreach (var list in obj)
{
list.CompanyCode = list.CompanyCode;
list.CummulativeAmount = list.CummulativeAmount;
list.Percentage = list.Percentage;
list.ModifiedDate = DateTime.UtcNow;
list.ModifiedDate = list.ModifiedDate;
list.Status = EntityStatus.Active;
_taxhistoryrepo.DbSetEntity.Add(list);
await _taxhistoryrepo.DbContext.SaveChangesAsync();
await Task.FromResult(_repository.SingleSave(obj));
}
通过obj进行迭代,因此“列表”为TaxLaw,但在这里:
_taxhistoryrepo.DbContext.SaveChangesAsync()
您将TaxLaw类型添加到TaxHistory表中
我也相信这里是您的错字
list.CompanyCode = list.CompanyCode;
...
基本上是用相同的变量设置相同的变量
我想您想实现的目标是:
public async Task<bool> SaveOrUpdate(IEnumerable<TaxLaw> obj)
{
using (var trans = _taxhistoryrepo.DbContext.Database.BeginTransaction())
{
var lists = new List<TaxTableHistory>();
foreach (var list in obj)
{
var taxHistory = new TaxHistory();
taxHistory.CompanyCode = list.CompanyCode;
taxHistory.CummulativeAmount = list.CummulativeAmount;
taxHistory.Percentage = list.Percentage;
taxHistory.ModifiedDate = DateTime.UtcNow;
taxHistory.ModifiedDate = list.ModifiedDate;
taxHistory.Status = EntityStatus.Active;
//manually mapped TaxLaw into TaxHistory
_taxhistoryrepo.DbSetEntity.Add(taxHistory); // save TaxHistory
await _taxhistoryrepo.DbContext.SaveChangesAsync();
await Task.FromResult(_repository.SingleSave(list)); //here save "list" not obj as you would save whole collection each iteration of the loop
}
trans.Commit();
}
return true;
}
关于c# - 无法从一种模型转换为另一种模型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53646590/