How to capture line index from an excel spreadsheet? In my code I'm determining that the int i variable gets the value 4, and adds i ++, passing the variable inside the log, so that it skips the header and that is from 1 to 5 and captures the index from the next line, I am using the foreach inside my treading method and I'm working with DataRow. Can someone give me a hand?
My cod:
private System.Threading.Tasks.Task TableProcessing(IEnumerable<DataRow> dataparam, int i, User UserLogged)
{
i = 4;
Action<object> processing = (data) =>
{
/*if (NHibernate.Context.ThreadStaticSessionContext.HasBind(NhibernateHelper.SessionFactory.))*/
NHibernate.Context.ThreadStaticSessionContext.Bind(NhibernateHelper.HelpThreading().OpenSession());
foreach (var line in (IEnumerable<DataRow>)data)
{
i++;
List<Process> listProcessExisting = new List<Process>();
Process process = null;
Interested interested = new Interested();
//search for the process by the previous or current judicial number
if (!line.ItemArray[1].ToString().Equals(""))
process = aplProcess.consultPerNProcessER(line.ItemArray[1].ToString());
if (process == null)
{
if (!line.ItemArray[2].ToString().Equals(""))
process = aplProcess.consultPerNProcessER(linha.ItemArray[2].ToString());
}
//search the interested by cpf / cnpj, cpf / cnpj is an identification of the interested party.
if (line.ItemArray[7].ToString().Length == 14)
interested = aplaplInterested.ConsultPerCPF(AuxiliarCPF_CNPJ.DeformationCPF(line.ItemArray[7].ToString()));
if (line.ItemArray[7].ToString().Length == 18)
interested = aplInterested.ConsultPerCPF(HelpCPF_CNPJ.DeformationCNPJ(line.ItemArray[7].ToString()));
if (process != null)
{
//if the process is not null I search all procinter related to it.
List<ProcessInterested> listprocessinterested = aplProcessInterested.consultPerIdProcess(process.Code);
if (listprocessinterested.Exists(o => o.Interested == interested))
log.Append("The interested "+ process.Interested.Name +", entered in the line "+ (i + 1) +" was added back to the process "+ process.NumberProcessjudicial + " <br>");
setProcessInterested(process, interested, line, i);
}
else
{
//New Process - 6.3
process = new Process();
process.Interested = interested;
}
}
}
}
I was able to solve my problem as follows:
protected void importar_Click(object sender, EventArgs e)
{
DataTable Dados = new DataTable();
Dados = DadosExcel(Excel);
Dados.Columns.Add("indice", typeof(int));
int i = 1;
foreach (DataRow linha in Dados.Rows)
{
linha["index"] = i;
i++;
}
}
Related
I'm working on an application that reads emails, extracts data from them and prints them in DataGrid (as alerts or notifications). The data is stored in a DB.
Here's the scenario:
A new email with data arrives, if a new alert does not arrive within a specific time slot(say within 5 minutes) from the same customer, with the opposite result(e.g. 1st alert was FAIL, 2nd SUCCESS => negation), the alert in the Datagrid is just updated.
Where is my problem:
In the part where I want to update the alert, a new alert is added, which causes a duplicate and the table is confused. And it does not update when new negation alert arrives.
NOTICE:
My application is larger, to better demonstrate my problem, the example is in the consol application.
But with a few modifications, the code is the same
Here is my code:
Method, which read and extract data
public void MailKitLib(EmailParser emailParser)
{
using (var client = new ImapClient())
{
using (var cancel = new CancellationTokenSource())
{
client.Connect(emailParser.ServerName, emailParser.Port, emailParser.isSSLuse,
cancel.Token);
client.Authenticate(emailParser.Username, emailParser.Password, cancel.Token);
var inbox = client.Inbox;
inbox.Open(FolderAccess.ReadOnly, cancel.Token);
Console.WriteLine("Total messages: {0}", inbox.Count);
Console.WriteLine("Recent messages: {0}", inbox.Unread);
for (int i = 0; i < inbox.Count; i++)
{
var message = inbox.GetMessage(i, cancel.Token);
MyAlert alert = new MyAlert(message.MessageId, message.Date.DateTime, message.Subject, message.Subject);
if (!MyAlert.alerts.Any(x => x.Id.Equals(alert.Id)))
{
MyAlert.alerts.Add(alert);\\Think of it as a method that saves the object to the database
}
CheckForUpdates(MyAlert.alerts[i]);
}
}
client.Disconnect(true);
}
}
Method checking for updates
public void CheckForUpdates(MyAlert alert)
{
double result = 0;
foreach (var item in MyAlert.alerts.Select(x => x.NameOfCustomer.Equals(alert.NameOfCustomer)))
{
if (item)
{
for (int i = 0; i < MyAlert.alerts.Count(); i++)
{
result = MyAlert.alerts[i].Date.Minute - alert.Date.Minute;
Console.WriteLine("Result of:" + MyAlert.alerts[i].NameOfCustomer + " " +
"and" + " " + alert.NameOfCustomer + " " + "is:" + result);
if (result > 0 && result <= 5)
{
Console.WriteLine("You HAVE TO UPDATE this" + " " + MyAlert.alerts[i].NameOfAlert);
MyAlert.alerts[i].NameOfAlert = "UPDATED";
break;
}
else
{
Console.WriteLine("You DON'T have to UPDATE this:" + " " + MyAlert.alerts[i].NameOfAlert);
}
}
}
}
Console.WriteLine("Wave:" + MyAlert.alerts.Count);
}
This is how I figured this out with DB
public double GetInterval(DateTime a, DateTime b)
{
return a.Subtract(b).TotalMinutes;
}
public void FindUpdate(Alert newAlert, Alert matchAlert)
{
//If new Alerts arrives from same customer with same problem till five 5 minutes
if (dAOAlert.GetAll().Any(x => x.Email.Equals(newAlert.Email) && x.Problem.NameOfAlert.Equals(newAlert.Problem.NameOfAlert))
&&
GetInterval(newAlert.Date, matchAlert.Date) > 0 && GetInterval(newAlert.Date, matchAlert.Date) <= 5)
{
//Find that Alert, and update his variables from alert, else save new alert
var item = dAOAlert.GetAll().FirstOrDefault(x => x.Email.Equals(newAlert.Email) && x.Problem.NameOfAlert.Equals(newAlert.Problem.NameOfAlert));
dAOAlert.Update(item, newAlert);
dAOAlert.Delete(newAlert);
LoadAlertGrid();
}
}
And this is how I have used this in Main method
for (int i = 0; i < inbox.Count; i++)
{
var message = inbox.GetMessage(i, cancel.Token);
GetBodyText = message.TextBody;
Problem problem = new Problem(message.MessageId);
if (!dAOProblem.GetAll().Any(x => x.Message_Id.Equals(problem.Message_Id)))
{
dAOProblem.Save(problem);
Alert alert = new Alert(message.MessageId, message.Date.DateTime, message.From.ToString(), 1, problem.Id);
if (!dAOAlert.GetAll().Any(x => x.Id_MimeMessage.Equals(alert.Id_MimeMessage)))
{
dAOAlert.Save(alert);
foreach (var item in dAOAlert.GetAll())
{
FindUpdate(alert, item);
}
LoadAlertGrid();
}
else
{
MessageBox.Show("Duplicate");
}
}
}
I am exporting Outlook contacts with a custom form to CSV from a specific Contacts folder. This folder is not the default location. It is a large folder with almost 7,000 contacts. This is a shared mailbox in Office 365, but we can't use the Outlook or Graph APIs because of the custom data.
My code below works fine, except that after iterating through 200-800 contacts, I get this error: "RPC Server is unavailable. (Exception from HRESULT: 0x800706BA)."
I also tried exporting the folder to a .pst and accessing that folder on my local machine. The result is essentially the same. UPDATE: I've been watching Outlook.exe in the task manager, and it steadily increases its memory consumption to around 300MB before crashing. I've tried the same code on a laptop running Office 2010, and I get an "Out of Memory" error.
I get the error whether Outlook is open or closed, but closing Outlook during program operation will immediately trigger this error. Outlook either starts (or restarts) following this error. I've read a number of SO posts and articles related to this error, but I'm not sure exactly what's going on. Any help is appreciated.
UPDATE: Code has been updated to use for loops instead of foreach loops per Dmitry Streblechenko's suggestion.
using System;
using Microsoft.Office.Interop.Outlook;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
namespace OutlookContacts
{
class Program
{
static void Main(string[] args)
{
var encoding = Encoding.UTF8;
string csvPath = #"myCSVPath";
Application outlook = new Application();
NameSpace ns = outlook.GetNamespace("MAPI");
MAPIFolder sharedContacts;
string recipientName = "myEmail#myDomain";
StringBuilder headerRow = new StringBuilder();
Recipient recip = ns.CreateRecipient(recipientName);
StreamWriter writer = new StreamWriter(csvPath, false, encoding);
recip.Resolve();
if (recip.Resolved)
{
try
{
//EntryID and StoreID of my folder
sharedContacts =
ns.GetFolderFromID(
"myEntryID",
"myStoreID"
);
Items contacts = sharedContacts.Items;
//Writing header row
ContactItem first = contacts.GetFirst();
var properties = first.ItemProperties;
for(int i = 0; i < properties.Count; i++)
{
try
{
headerRow.Append(string.Format("\"{0}\",", properties[i].Name));
}
catch (System.Exception ex)
{
headerRow.Append(string.Format("{0},", ex.Message));
}
}
headerRow.AppendLine(Environment.NewLine);
WriteToCSV(writer, headerRow);
Console.WriteLine("Header row written;");
Marshal.ReleaseComObject(properties);
Marshal.ReleaseComObject(first);
//Writing Records
for (int i = 1; i <= contacts.Count; i++)
{
object o = contacts[i];
if (o is ContactItem)
{
ContactItem contact = (ContactItem)o;
if (contact != null)
{
Console.Write(contact.FullName);
StringBuilder dataRow = new StringBuilder();
ItemProperties contactProps = contact.ItemProperties;
for (int j = 0; j < contactProps.Count; j++)
{
ItemProperty property = contactProps[j];
try
{
if (property.Value == null)
{
string value = "null,";
dataRow.Append(value);
}
//else if (property.Name == "Attachments")
//{
// //Attachment file names
// string attachment = "";
// for (int k = 1; k < contact.Attachments.Count; k++)
// {
// attachment = (string.Format("\"{0}\"; ", contact.Attachments[k].FileName));
// dataRow.Append(attachment);
// }
// dataRow.Append(",");
//}
else
{
string value = property.Value.ToString();
value = value.Replace("\r\n\r\n\r\n", "\r\n")
.Replace("\r\n\r\n", "\r\n")
.Replace("\"", "'");
value = (string.Format("\"{0}\",", value));
dataRow.Append(value);
}
}
catch (System.Exception ex)
{
string value = string.Format("{0}: {1},", property.Name, ex.Message);
dataRow.Append(value);
}
Marshal.ReleaseComObject(property);
}
dataRow.Append(Environment.NewLine);
WriteToCSV(writer, dataRow);
Marshal.ReleaseComObject(contactProps);
Marshal.ReleaseComObject(contact);
}
Marshal.ReleaseComObject(o);
counter++;
Console.WriteLine(": Written " + counter);
}
}
}
catch (System.Exception ex)
{
Console.WriteLine(dataRow.ToString(), ex.Message);
Console.ReadKey();
}
}
}
static void WriteToCSV(StreamWriter writer, StringBuilder row)
{
var data = row.ToString();
writer.WriteAsync(data);
}
}
}
Looks like you are running out of RPC channels. You need to avoid using foreach loops (they tend to keep all collection members referenced until the loop exits) and explicitly release all COM objects are soon as you are done with them.
Off the top of my head:
for(int i = 1; i <= contacts.Count; i++)
{
obejct o = contacts[i];
ContactItem contact = o as ContactItem;
if (o != null)
{
ItemProperties properties = contact.ItemProperties;
StringBuilder newLine = new StringBuilder();
for (int j = 1; j <= properties.Count; j++)
{
ItemProperty property = properties[j];
var value = "";
if (property.Value == null)
{
value = "null,";
Console.WriteLine(value);
newLine.Append(value);
}
else
{
value = property.Value.ToString() + ",";
newLine.Append(value);
}
Marshal.ReleaseComObject(property);
}
newLine.Append(Environment.NewLine);
WriteToCSV(writer, newLine);
Marshal.ReleaseComObject(properties);
Marshal.ReleaseComObject(contact);
}
Marshal.ReleaseComObject(o);
}
About my Program:
My algorithm(this class) is meant to check whether a delivery has been finished and afterwards makes the truck/trailer/driver available for another delivery, at the same time this algorithm sends another truck/trailer/driver on a delivery. To sum it up this class does the following:
Check whether a booking is in Allocation mode (Allocation mode basically means that the "booking" is in progress of being delivered
Check whether there is tonnage left of the booking (Ex. I want to sent 500 ton to a place, but a delivery can only be 30 ton at a time so it checks if there is still ton that needs to be delivered)
To make the Driver(s)/Truck(s)/Trailer(s) available that finished their delivery.
To automatically allocate tonnage to a Driver/Trailer/Truck.
Deleting entries that are finished (any bookings that are finished - Logs still stay in the database).
My Problem:
I have no idea what is wrong with my class, I have been hours at it and can't seem to figure out what is causing my boolean variable (forLoopBreak) to trigger a "false" value when it is calling the method checkAvailTrailers(). The problem seems to be in there but I can't figure out what causes the problem.
Class:
[https://pastebin.com/4up8eppd][1]
( I couldn't paste it here as I met the limit of characters)
Notes:
I know my programming looks but, but I am still new to this.
I decided to attach the whole class as the problem may be at a different place.
Edit:
My code is too large to investigate so here is the relevant parts:
private void startAlgo()
{
checkAvailTrailers();
if (forloopBreak == false)
{
setErrorMessage("Avail Trailers not enough!");
}
}
private void checkAvailTrailers()
{
string trailerRouteAllocation = null;
string trailerVragAllocation = null;
string tempHolderTrailer = null;
string myNewTempT = null;
string trailermyTemp = null;
int trailerCount = 0;
int tempTra = -1;
//Gets trailer route classification
using (SqlCommand selectTrailer = new SqlCommand("SELECT [TR_Routes] FROM dbo.TrailerDetail WHERE [TR_Allocation] = " + 0, con))
{
using (SqlDataReader reader = selectTrailer.ExecuteReader())
{
while (reader.Read())
{
trailerRouteAllocation = reader.GetString(0);
tempHolderTrailer = trailerRouteAllocation;
myNewTempT = trailerRouteAllocation;
for (int l = 0; l < tempHolderTrailer.Length; l++)
{
tempTra = myNewTempT.IndexOf(",");
if (tempTra >= 0)
{
trailermyTemp = myNewTempT.Substring(0,tempTra);
}
else
{
trailermyTemp = myNewTempT;
if (trailermyTemp == myCurrentBookingRoute.ToString())
{
mycurrentTrailerAvailableRoute[trailerCount] = tempHolderTrailer;
}
break;
}
myNewTempT = myNewTempT.Substring(tempTra + 1);
if (trailermyTemp == myCurrentBookingRoute.ToString())
{
mycurrentTrailerAvailableRoute[trailerCount] = trailerRouteAllocation;
}
}
trailerCount++;
}
reader.Close();
}
}
//gets trailer vrag classification.
int countTrailerVrag = 0;
for (int l = 0; l < mycurrentTrailerAvailableRoute.Length; l++)
{
if (mycurrentTrailerAvailableRoute[l] != null)
{
using (SqlCommand select = new SqlCommand("Select [TR_Classification] FROM dbo.TrailerDetail WHERE [TR_Routes] = '" + mycurrentTrailerAvailableRoute[l] + "' AND [TR_Allocation] = " + 0, con))
{
using (SqlDataReader readerS = select.ExecuteReader())
{
while (readerS.Read())
{
trailerVragAllocation = readerS.GetString(0);
myAvailableTrailerVragClassification[countTrailerVrag] = trailerVragAllocation;
countTrailerVrag++;
}
readerS.Close();
}
}
}
}
int countTrailers = 0;
string trailerRegNum = null;
for (int l = 0; l < mycurrentTrailerAvailableRoute.Length; l++)
{
if (mycurrentTrailerAvailableRoute[l] != null)
{
using (SqlCommand selectT = new SqlCommand("Select [TR_RegNumber] FROM dbo.TrailerDetail WHERE [TR_Routes] = '" + mycurrentTrailerAvailableRoute[l] + "'" + " AND [TR_Classification] = '" + myAvailableTrailerVragClassification[l] + "' AND [TR_Allocation] = " + 0, con))
{
SqlDataReader readerT = selectT.ExecuteReader();
if (readerT.HasRows)
{
while (readerT.Read())
{
trailerRegNum = readerT.GetString(0);
myAvailableCurrentTraillerRegNumber[countTrailers] = trailerRegNum;
countTrailers++;
}
}
else
{
forloopBreak = false;
}
readerT.Close();
}
}
}//END OF TRAILER CHECKING
//gets trailer's max tonnage
int myTrailerTonMax = 0;
int myTrailerTon = 0;
for (int l = 0; l < mycurrentTrailerAvailableRoute.Length; l++)
{
if (mycurrentTrailerAvailableRoute[l] != null)
{
using (SqlCommand selectT = new SqlCommand("Select [TR_MaxTonnage] FROM dbo.TrailerDetail WHERE [TR_Routes] = '" + mycurrentTrailerAvailableRoute[l] + "'" + " AND [TR_Classification] = '" + myAvailableTrailerVragClassification[l] + "'", con))
{
using (SqlDataReader readerS = selectT.ExecuteReader())
{
while (readerS.Read())
{
myTrailerTon = readerS.GetInt32(0);
myTrailerAvailableTonMax[myTrailerTonMax] = myTrailerTon;
myTrailerTonMax++;
}
readerS.Close();
}
}
}
}
}
Extra:
- The data in my database matches the criteria, the while loop even executes but in the end my boolean value returns a false.
The readerT.HasRows clause will always be true if there is any data initially in the reader. Here is the property's description from the MSDN page
Gets a value that indicates whether the SqlDataReader contains one or more rows.
What you want to do instead (I assume) is set forloopBreak = false; when the while loop is finished. So inside the using block you put this:
SqlDataReader readerT = selectT.ExecuteReader();
while (readerT.Read())
{
trailerRegNum = readerT.GetString(0);
myAvailableCurrentTraillerRegNumber[countTrailers] = trailerRegNum;
countTrailers++;
}
forloopBreak = false;
readerT.Close();
Let me know if this works!
I am using Data Grid to show passbook balance. I have done everything I'm unable to get the balance value in the respective column.
private void dgview2_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
int credit1, debit1;
int balance = new int();
if (int.TryParse(dgview2.Rows[e.RowIndex].Cells["debit"].Value.ToString(),
out debit1) && int.TryParse(dgview2.Rows[e.RowIndex].Cells["credit"].Value.ToString(),
out credit1) && int.TryParse(dgview2.Rows[e.RowIndex].Cells["balance"].Value.ToString(),
out balance))
{
balance = balance + credit1 - debit1;
dgview2.Rows[e.RowIndex].Cells["balance"].Value = balance.ToString();
}
}
Vfp9sp2 Application output
here is the code which i am useing to populate grid
private void fill_div()
{
var com = new MySqlCommand("Select *From shtrn where mem_no ='" + textBox1.Text + "' order by tdate ", con_db.con);
var dr = com.ExecuteReader();
try
{
dgview2.Rows.Clear();
while (dr.Read())
{
var n = dgview2.Rows.Add();
dgview2.Rows[n].Cells[0].Value = Convert.ToDateTime(dr["tdate"].ToString());
dgview2.Rows[n].Cells[1].Value = dr["particular"].ToString();
dgview2.Rows[n].Cells[2].Value = dr["trmode"].ToString();
dgview2.Rows[n].Cells[3].Value = dr["debit"].ToString();
dgview2.Rows[n].Cells[4].Value = dr["credit"].ToString();
dgview2.Rows[n].Cells[5].Value = dr["balance"].ToString();
dgview2.FirstDisplayedScrollingRowIndex = n;
dgview2.CurrentCell = dgview2.Rows[n].Cells[0];
UpdateBalance();
}
{
dr.Close();
}
}
catch (FormatException)
{
MessageBox.Show("No Records Found ");
}
}
The reason code does not work is that grid is made read only, therefore code specified in the event handler (dgview2_CellEndEdit) is not triggered.
Ideally you should be making balance calculations before updating the grid, but as a quick workaround you can move the code to a private method like this:
private void UpdateBalance()
{
for (int i = 0; i < dgview2.Rows.Count; i++)
{
int credit1, debit1, balance;
if (int.TryParse(dgview2.Rows[i].Cells[3].Value.ToString(),
out debit1) && int.TryParse(dgview2.Rows[i].Cells[4].Value.ToString(),
out credit1) && int.TryParse(dgview2.Rows[i].Cells[5].Value.ToString(),
out balance))
{
balance = balance + credit1 - debit1;
dgview2.Rows[i].Cells[5].Value = balance.ToString();
}
}
}
Then call this method after you finished populating the grid:
UpdateBalance();
The method iterates over each row and updates balance cells using the same logic.
[Edit for update code]
Instead of above, you can perform calculation in your update logic as below:
while (dr.Read())
{
var n = dgview2.Rows.Add();
dgview2.Rows[n].Cells[0].Value = Convert.ToDateTime(dr["tdate"].ToString());
dgview2.Rows[n].Cells[1].Value = dr["particular"].ToString();
dgview2.Rows[n].Cells[2].Value = dr["trmode"].ToString();
dgview2.Rows[n].Cells[3].Value = dr["debit"].ToString();
dgview2.Rows[n].Cells[4].Value = dr["credit"].ToString();
dgview2.Rows[n].Cells[5].Value = dr["balance"].ToString();
int credit1, debit1, balance;
if (int.TryParse(dr["debit"].ToString(),
out debit1) && int.TryParse(dr["credit"].ToString(),
out credit1) && int.TryParse(dr["balance"].ToString(),
out balance))
{
dgview2.Rows[n].Cells[5].Value = balance + credit1 - debit1;
}
dgview2.FirstDisplayedScrollingRowIndex = n;
dgview2.CurrentCell = dgview2.Rows[n].Cells[0];
}
I am writing a small data migration tools from one big database to another small database. All of the others data migration method worked satisfactorily, but the following method has given an exception from the SKIP VALUE IS 100. I run this console script remotely as well as inside of the source server also. I tried in many different was to find the actual problem what it is. After then I found that only from the SKIP VALUE IS 100 it is not working for any TAKE 1,2,3,4,5 or ....
Dear expertise, I don't have any prior knowledge on that type of problem. Any kind of suggestions or comments is appreciatable to resolve this problem. Thanks for you time.
I know this code is not clean and the method is too long. I just tried solve this by adding some line of extra code. Because the problem solving is my main concern. I just copy past the last edited method.
In shot the problem I can illustrate with this following two line
var temp = queryable.Skip(90).Take(10).ToList(); //no exception
var temp = queryable.Skip(100).Take(10).ToList(); getting exception
private static void ImporterDataMigrateToRmgDb(SourceDBEntities sourceDb, RmgDbContext rmgDb)
{
int skip = 0;
int take = 10;
int count = sourceDb.FormAs.Where(x=> x.FormAStateId == 8).GroupBy(x=> x.ImporterName).Count();
Console.WriteLine("Total Possible Importer: " + count);
for (int i = 0; i < count/take; i++)
{
IOrderedQueryable<FormA> queryable = sourceDb.FormAs.Where(x => x.FormAStateId == 8).OrderBy(x => x.ImporterName);
List<IGrouping<string, FormA>> list;
try
{
list = queryable.Skip(skip).Take(take).GroupBy(x => x.ImporterName).ToList();
//this line is getting timeout exception from the skip value of 100.
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
sourceDb.Dispose();
rmgDb.Dispose();
sourceDb = new SourceDBEntities();
rmgDb = new RmgDbContext();
skip += take;
continue;
}
if (list.Count > 0)
{
foreach (var l in list)
{
List<FormA> formAs = l.ToList();
FormA formA = formAs.FirstOrDefault();
if (formA == null) continue;
Importer importer = formA.ConvertToRmgImporterFromFormA();
Console.WriteLine(formA.FormANo + " " + importer.Name);
var importers = rmgDb.Importers.Where(x => x.Name.ToLower() == importer.Name.ToLower()).ToList();
//bool any = rmgDb.Importers.Any(x => x.Name.ToLower() == formA.ImporterName.ToLower());
if (importers.Count() == 1)
{
foreach (var imp in importers)
{
Importer entity = rmgDb.Importers.Find(imp.Id);
entity.Country = importer.Country;
entity.TotalImportedAmountInUsd = importer.TotalImportedAmountInUsd;
rmgDb.Entry(entity).State = EntityState.Modified;
}
}
else
{
rmgDb.Importers.Add(importer);
}
rmgDb.SaveChanges();
Console.WriteLine(importer.Name);
}
}
skip += take;
}
Console.WriteLine("Importer Data Migration Completed");
}
I have fixed my problem by modifying following code
var queryable =
sourceDb.FormAs.Where(x => x.FormAStateId == 8)
.Select(x => new Adapters.ImporterBindingModel()
{
Id = Guid.NewGuid().ToString(),
Active = true,
Created = DateTime.Now,
CreatedBy = "System",
Modified = DateTime.Now,
ModifiedBy = "System",
Name = x.ImporterName,
Address = x.ImporterAddress,
City = x.City,
ZipCode = x.ZipCode,
CountryId = x.CountryId
})
.OrderBy(x => x.Name);