-Image on top Codes Below....
private void Save_FGARec()
{
try
{
for(int x= 0; x < FGAdataGrid.Rows.Count; x++)
{
sysSFCDBDataContext SFC = new sysSFCDBDataContext();
Sales_FGAllocated FGA = SFC.Sales_FGAllocateds.FirstOrDefault(r => r.RowID == Convert.ToInt64(FGAdataGrid.Rows[x].Cells[0].Value));
if (FGAdataGrid.Rows[x].Cells[0].Value != null)
{
FGA.TotalLoaded = Convert.ToInt64(FGAdataGrid.Rows[x].Cells[6].Value);
SFC.SubmitChanges();
}
else
{
SFC.Connection.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
-- Is my Code on Update Right? I'm confuse coz my table doesn't update what i store on this column totalloaded which counts as cell[8]... did i missed something here?
try below, not sure this will solve the issue, but may be you are not dispose/ close the data context correctly with current code. you can use using block like below
using (sysSFCDBDataContext SFC = new sysSFCDBDataContext())
{
Sales_FGAllocated FGA = SFC.Sales_FGAllocateds.FirstOrDefault(r => r.RowID == Convert.ToInt64(FGAdataGrid.Rows[x].Cells[0].Value));
if (FGAdataGrid.Rows[x].Cells[0].Value != null)
{
FGA.TotalLoaded = Convert.ToInt64(FGAdataGrid.Rows[x].Cells[6].Value);
SFC.SubmitChanges();
}
}
Related
I am trying to delete over 5000 records from the database using .netCore 2.1. I have the following method which works fine however it takes way too long.
public async Task<bool> deleteAdhocDetails(int[] id)
{
var status = false;
for (var x = 0; x < id.Length; x++)
{
var existingReward = await _context.AdhocRewardInfo
.Where(d => d.RowID == id[x])
.FirstOrDefaultAsync<AdhocRewardInfo>();
if ((existingReward != null) && (existingReward.HaloRewardCode != null))
{
try
{
//removing existingReward
_context.AdhocRewardInfo.Remove(existingReward);
await _context.SaveChangesAsync();
status = true;
}
catch (Exception e)
{
throw e;
}
}
}
return status;
}
I am currently using EFCore.BulkExtensions for inserting records and it works nicely. I tried using BulkDelete but it didn't seem to make a difference. I also tried to use Z.EntityFramework.Extensions.EFCore but couldn't get that to work too. I should also mention that I am kinda new to this. If someone could please point me in the right direction I would appreciate it. Thanks
In the adhoc.service.ts:
deleteAdhocRecipients(id: number[]): Promise<boolean> {
return this.http.put<boolean>(this.baseUrl + 'deleteAdhocDetails', id)
.toPromise();
}
and in the .ts file:
this.general
.load(this.aService.deleteAdhocCampaign(this.adhocForm.get('create.id').value))
.then(
y => {
if (deleteArr.length > 0) {
this.general.load(this.aService.deleteAdhocRecipients(deleteArr))
.then(
f => this.router.navigate(['/adhoc-campaign/lookup'])
);
} else {
this.router.navigate(['/adhoc-campaign/lookup']);
}
}
);
I optimized your c# code
public async Task<bool> deleteAdhocDetails(int[] id){
try{
var deletedRecords= await _context.AdhocRewardInfo.Where(d =>
id.Contains(d.RowID))
foreach (var item in deletedRecords)
{
_context.AdhocRewardInfo.Remove(item );
}
await _context.SaveChangesAsync();
return true;
}catch (Exception e){
return false;
}
}
You can remove select of object and then do only one saveChanges
public async Task<bool> deleteAdhocDetails((int id, object haloRewardCode)[] id)
{
try
{
for (var x = 0; x < id.Length; x++)
{
var existingReward = new AdhocRewardInfo() { id = id[x].id, HaloRewardCode = id[x].haloRewardCode };
if ((existingReward != null) && (existingReward.HaloRewardCode != null))
{
//removing existingReward
_context.AdhocRewardInfo.Remove(existingReward);
}
}
}
catch (Exception e)
{
throw;
}
await _context.SaveChangesAsync();
return true;
}
I would suggest to use linq2db.EntityFrameworkCore (disclaimer: I'm one of the creators).
And Delete will be fast as possible:
var deletedCount = await _context.AdhocRewardInfo
.Where(d => id.Contains(d.RowID))
.DeleteAsync();
I think the fastest way will be using sql query string
public async Task<bool> deleteAdhocDetails(int[] id)
{
var ids= string.Join(",",id);
var rows= await _context.Database.ExecuteSqlRawAsync(
"DELETE FROM AdhocRewardInfo WHERE Id IN ("+ ids + ")");
return rows>0;
}
I am trying to fetch data from CRM using this API. I get an error
Runtime binding on a null reference
whenever I try to get value from data.fullname. Is there any way I can fix it?
Thanks
var response = httpClient.GetAsync("contacts?$select=fullname,emailaddress1").Result;
if (response.IsSuccessStatusCode)
{
var accounts = response.Content.ReadAsStringAsync().Result;
var jRetrieveResponse = JObject.Parse(accounts);
dynamic collContacts = JsonConvert.DeserializeObject(jRetrieveResponse.ToString());
try
{
foreach (var data in collContacts.value)
{
// You can change as per your need here
if (data.fullname.Value != null)
{
success[i] = data.fullname.Value;
}
i ++;
}
}
catch (Exception)
{
throw;
}
}
Replace
if (data.fullname.Value != null)
with this
if (!String.IsNullOrWhiteSpace(data.fullname.Value))
OR Replace
try
{
foreach (var data in collContacts.value)
{
// You can change as per your need here
if (data.fullname.Value != null)
{
success[i] = data.fullname.Value;
}
i ++;
}
}
catch (Exception)
{
throw;
}
With
try
{
foreach (var data in collContacts.value)
{
success[i] = data?.fullname?.Value;
i ++;
}
}
catch (Exception)
{
throw;
}
var randnumber = CommonClass.Generate8DigitHBFNumber();
bool CheckCaseRef = CheckCaseRefIdAlreadyExistsInDB(randnumber);
if (CheckCaseRef)
{
randnumber = CommonClass.Generate8DigitHBFNumber();
}
else
{
randnumber = CommonClass.Generate8DigitHBFNumber();
}
//Method to Check the generated random number
bool CheckCaseRefIdAlreadyExistsInDB(string randnumber)
{
Log.Info("CheckCaseRefIdAlreadyExistsInDB started...");
bool checkCaseRef = false;
try
{
var ObjCustomerList = db.tblCustomers.ToList();
if (ObjCustomerList != null)
{
foreach (var customerlst in ObjCustomerList)
{
if (!(string.IsNullOrEmpty(randnumber)))
{
if (customerlst.CaseRef == randnumber)
{
checkCaseRef = true;
break;
}
}
}
}
else
{
return checkCaseRef;
}
}
catch (Exception ex)
{
Log.Error("Error CheckCaseRefIdAlreadyExistsInDB started...", ex);
return false;
}
return checkCaseRef;
}**
You might want to do this:
var randnumber = CommonClass.Generate8DigitHBFNumber();
while (! CheckCaseRefIdAlreadyExistsInDB(randnumber))
{
randnumber = CommonClass.Generate8DigitHBFNumber();
}
bool CheckCaseRefIdAlreadyExistsInDB(string randnumber)
{
return db.tblCustomers.Any(c => c.CaseRef == randnumber ?? "");
}
Checking the regenerated one would be an excellent use for recursion. If you don't know much about recursion, I would highly recommend doing some research on it first though, as it can lead to some really nasty memory issues in your code if used incorrectly.
//Code in main method
string randnumber = CheckRandomNumber();
//Recursive method to call
public string CheckRandomNumber()
{
string numToCheck = CommonClass.Generate8DigitHBFNumber();
if (db.tblCustomers.Any(x => x.CaseRef == numToCheck))
{
//Duplicate was found
CheckRandomNumber();
}
return numToCheck;
}
Well, i have a Model with a collection saving changes in a loop structure
foreach(Customer objCustomer in listCustomer)
{
try
{
db.Customer.Add(objCustomer);
db.SaveChanges();
}
catch(Exception ex)
{
db.Entry(objCustomer).State = EntityState.Detach;
}
}
When it throws me any exception in a collection related to entity, the next ones keeps throwing exceptions.
I tried to detach the entire collection but it didn't work
foreach(Customer objCustomer in listCustomer)
{
try
{
db.Customer.Add(objCustomer);
db.SaveChanges();
}
catch(Exception ex)
{
for (int i = 0; i < objCustomer.Address; i++)
{
db.Entry(objCustomer.Address[i]).State = EntityState.Detach;
}
db.Entry(objCustomer).State = EntityState.Detach;
}
}
Any suggestion?
I don't know why but it works, i used like it refers in this post
EntityCollection Clear() and Remove() methods
objCustomer.Address.ToList().ForEach(x => db.Entry(x).State = EntityState.Detached);
It is almost as i did before using "for"
Thanks anyway everyone
i thought that the exception of second code maybe has been never occurred?
In addition,your code has any transaction ?
Try this? Warning not tested!
using(var db = new Context())
{
foreach(Customer objCustomer in listCustomer)
{
var exists = db.Customer.FirstOrDefault(x => x.CustomerID == objCustomer.CustomerID;
if( exists = null)
{
db.Customer.Add(objCustomer);
}
else
{
db.Entry(objCustomer).State = EntityState.Modified;
}
db.SaveChanges();
}
}
The code below is not working. (no exceptions thrown). Totally clueless why is not changed When I check in the GUI, there is a new version, with no changes!
public static void SetEntityWebName(ProcessEntity entity, SPWeb entityWeb)
{
try
{
entityWeb.AllowUnsafeUpdates = true;
var welcomePageListItem = entityWeb.GetFile(entityWeb.RootFolder.WelcomePage).Item;
var welcomePage = entityWeb.GetFile(entityWeb.RootFolder.WelcomePage);
welcomePage.CheckOut();
if (entity.Type == Entity.Job)
{
entityWeb.Title = ((SyncJobs_Result)entity.Entity).JobName;
welcomePageListItem["Title"] = ((SyncJobs_Result)entity.Entity).JobName;
welcomePage.Update();
}
if (entity.Type == Entity.Client)
{
entityWeb.Title = ((SyncClients_Result)entity.Entity).ClientName;
welcomePageListItem["Title"] = ((SyncClients_Result)entity.Entity).ClientName;
welcomePage.Update();
}
if (entity.Type == Entity.Opportunity)
{
entityWeb.Title = ((SyncOpportunities_Result)entity.Entity).OpportunityName;
welcomePageListItem["Title"] = ((SyncOpportunities_Result)entity.Entity).OpportunityName;
welcomePage.Update();
}
welcomePage.CheckIn(string.Empty);
welcomePage.Publish(string.Empty);
entityWeb.Update();
}
catch (Exception ex)
{
}
}
I think you also have to update the welcomePageListItem list item .
I am not sure but , give it a try