I am new to EF. I created entity models from database.
I have tables CurrencyMaster([FromCurrency],[ToCurrency],[ActiveStatus]) and CurrencyConversion([ID],[FromCurrency],[ToCurrency],[Date],[CurrencyFactor])
I am looping for the CurrencyMaster records and accordingly DownloadCurrencyRates will get me the List<CurrencyRate> objects.
I just want to add these objects to entity database.
I tried something like this
public DownloadStatus DownloadUpdateCurrency(DateTime toDate, DateTime fromDate)
{
CurrencyEntities db = new CurrencyEntities();
var curMasters = db.CurrencyMasters.Where(x => x.ActiveStatus == 0);
foreach (var item in curMasters)
{
var curcRatesList = DownloadCurrencyRates(fromDate, toDate,
item.FromCurrency, item.ToCurrency);
//I know this is a bad code
curcRatesList.Select(x =>
{
db.AddToCurrencyConversions(
new CurrencyEntity.CurrencyConversion {
Date = x.date,
CurrencyFactor = x.value,
FromCurrency = item.FromCurrency,
ToCurrency = item.ToCurrency
}
);
return true;
});
}
db.SaveChanges();
return DownloadStatus.DownloadSuccess;
}
How can I do the same in a proper way?
Is there any way I can do this without looping for curcRatesList?
I am using .NET 3.5, and not sure about EF version.. I didn’t try executing code(I need some other setup for that), but I am quite sure that what I am doing is not correct.. So I am posting here..
The procedure is correct. There is no bulk insert capability in EF that would allow to add a whole list of entities in a single method call. You must loop over the items and add them one by one.
As a side note: I would just use an ordinary
foreachloop instead of that strangeSelecttrick (which misuses theSelectmethod, but it will work). Or – ifcurcRatesListis of typeList<T>– you can use theForeachmethod ofList<T>instead ofSelect.