I am trying to update a record in my SQL database. I have 2 updates to different tables in the same database. 1 works fine and the other does not update on the SubmitChanges(). The code looks the same is there something i am missing?
public bool UpdateStockSizeInBomData(string drawingNumber, string stockSize)
{
using (var db = GetFordContext())
{
Data.BomData result = db.BomDatas.Where(b => b.sIdNoStk.Equals(drawingNumber)).FirstOrDefault();
if (null == result)
{
return false;
}
result.sDimensionsStk = stockSize;
db.SubmitChanges();
return true;
}
}
This one does not work. The database record comes in fine while debugging, and even changes but the update is never committed to the database. And there has been changes made.
public bool UpdateStockSizeInDrawingData(string jobNumber, string drawingNumber, string stockSize, string material)
{
using (var db = GetFordContext())
{
Data.DrawingData result = db.DrawingDatas.Where(dd => dd.GROB_TB_DrawingNumber.Equals(drawingNumber) && dd.Ford_Vendor_JobNumber.Equals(jobNumber)).FirstOrDefault();
if (null == result)
{
return false;
}
result.Ford_Det_StockSize = stockSize;
//result.Ford_Det_Material = material;
db.SubmitChanges();
return true;
}
}
Related
I have the following code that needs to return a single value. However, I keep on getting null (the field Notifications_Id = 0) even though it clearly exists in the database.
var role = _context.AssignedTickets.FirstOrDefault(a => a.Notifications_Id == incidence.Notifications_Id);
I am using Net Core 5
Below is my code
public async Task<ActionResult> EditTicket(int? id)
{
{
if (id == null)
{
return StatusCode(400);
}
Incidence incidence = await _context.Incidences.FindAsync(id);
if (incidence == null)
{
return StatusCode(401);
}
return View(incidence);
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditTicket(Incidence incidence)
{
var role = _context.AssignedTickets.FirstOrDefault(a => a.Notifications_Id == incidence.Notifications_Id);
if (role == null)
{
return StatusCode(404);
}
role.Status = "C";
role.ClosedOn = DateTime.Now;
if (ModelState.IsValid)
{
DateTime Timeup = (DateTime)role.ClosedOn;
DateTime Timedown = (DateTime)role.CreatedOn;
long DiffTicks = (Timedown - Timeup).Ticks;
role.TurnAroundTime = Math.Abs(DiffTicks).ToString();
_context.Entry(incidence).State = EntityState.Modified;
_context.SaveChangesAsync();
return RedirectToAction("Dashboard", "Agent");
}
return View(incidence);
}
Please use var role = _context.AssignedTickets.FirstOrDefault(a => a.Notifications_Id == 29); to get the object, and then compare whether the attributes inside match the database.
I read your post and all comments carefully. What everyone said is very reasonable, and the code in the post is not problematic.
So I think the problem is likely to be a problem with the string connecting to the database, that is, a different database is used.
I'm having trouble updating values in Entity Framework 6, I've looked thoroughly through the internet for answers but it seems I'm doing everything just fine, yet I can't seem to make it work.
It's worth mentioning that adding entities into the DB works just fine, meaning I can add products/users in my project to the DB, but not update them.
This is homework.
public bool ChangeAccountStatus(long userID, bool isUserActive)
{
User userToChange = GetUserById(userID); // Gets the user whose values I want to change.
using (var context = new ShopContext())
{
if (userToChange != null)
{
if (isUserActive)
{
userToChange.IsActive = false;
context.SaveChanges();
}
else
{
userToChange.IsActive = true;
context.SaveChanges();
}
return true;
}
return false;
}
}
I can make the update work if I use linq to find the user whose value I want to change, but I don't want too much code-duplication in my project, and I'm using the same linq (function GetUserById) in many other functions.
Do I need to use linq to access the user from the database, instead of using a function I created to avoid code-duplication?
This is the GetUserById function:
public User GetUserById(long userId)
{
using (var context = new ShopContext())
{
var userToFind = context.UsersTable
.Where((u) => u.Id == userId).FirstOrDefault();
if (userToFind != null)
return userToFind;
else
return null;
}
}
You are retrieving an entity from one context, then calling SaveChanges() on a different context. If you inline the method, it becomes more clear:
var userToChange;
using (var context = new ShopContext())
{
userToChange = context.UsersTable.Where((u) => u.Id == userId).FirstOrDefault();
}
using (var context = new ShopContext())
{
if (userToChange != null)
{
if (isUserActive)
{
userToChange.IsActive = false;
context.SaveChanges();
}
else
{
userToChange.IsActive = true;
context.SaveChanges();
}
return true;
}
return false;
}
The second context doesn't know anything about userToChange, because it isn't tracking it. You can tell it to though:
context.UsersTable.Attach(userToChange);
As an aside, you have some redundant code there - an if statement, which assigns a boolean to true or false can be simplified:
if (isUserActive)
userToChange.IsActive = false;
else
userToChange.IsActive = true;
// Equivalent to:
userToChange.IsActive = !isUserActive;
And the null check is not necessary:
if (userToFind != null)
return userToFind;
else
return null;
// Equivalent to:
return userToFind;
Here is my code
public static string UpdateEmptyCaseRevierSet() {
string response = string.Empty;
using (System.Transactions.TransactionScope tran = new System.Transactions.TransactionScope()) {
using (var db = new Entities.WaveEntities()) {
var maxCaseReviewersSetID = db.CaseReviewerSets.Select(crs => crs.CaseReviewersSetId).Max();
var emptyCHList = db.CaseHistories.Where(ch => ch.CaseReviewersSetID == null && ch.IsLatest == true && ch.StatusID != 100).ToList();
for(int i=0; i < emptyCHList.Count; i++) {
var emptyCH = emptyCHList[i];
var newCaseReviewerSET = new Entities.CaseReviewerSet();
newCaseReviewerSET.CreationCHID = emptyCH.CHID;
db.CaseReviewerSets.Add(newCaseReviewerSET);
emptyCH.CaseReviewerSet = newCaseReviewerSET;
}
db.SaveChanges();
}
tran.Complete();
}
return response;
}
The exception occures on "db.SaveChanges()"
I saw in another post with the same error message something about "it seems I cannot have two connections opened to the same database with the TransactionScope block." but I dont think that this has anything to do with my case.
Additionally the number of records to insert and update in total are 2700, witch is not that many really. But it does take quite a lot of time to complete the for statement (10 minutes or so). Since everything happening within the for statement is actually happening in the memory can someone please explane why is this taking so long ?
You can try as shown below using latest db.Database.BeginTransaction API.
Note : use foreach instead of for
using (var db = new Entities.WaveEntities())
{
using (var dbContextTransaction = db.Database.BeginTransaction())
{
try
{
var maxCaseReviewersSetID = db.CaseReviewerSets.Select(crs => crs.CaseReviewersSetId).Max();
var emptyCHList = db.CaseHistories.Where(ch => ch.CaseReviewersSetID == null && ch.IsLatest == true && ch.StatusID != 100).ToList();
foreach(var ch in emptyCHList) {
var newCaseReviewerSET = new Entities.CaseReviewerSet();
newCaseReviewerSET.CreationCHID = ch.CHID;
db.CaseReviewerSets.Add(newCaseReviewerSET);
}
db.SaveChanges();
dbContextTransaction.Commit();
}
catch (Exception)
{
dbContextTransaction.Rollback();
}
}
}
i created a data model and imported data table to it . then i created a object there and it didnt auto create
public MealGroup GrouoMealCode(string GroupmealCode)
{
return context.MealGroups.Where(c => c.IsDelete == false && c.MealGroupCode == GroupmealCode).FirstOrDefault();
}
here is my code and first i created a table called mealgroup then i imported it to the project . then also i added a class and create a method for creating a statement called GrouoMealCode to get the data from the table
public MealGroup GroupMealCode(string GroupmealCode)
{
return context.MealGroups.Where(c => c.IsDelete == false && c.MealGroupCode == GroupmealCode).FirstOrDefault();
}
public int SaveGroupMealDetils(MealGroup mealGroup)
{
try
{
meal = context.MealGroups.Where(c => c.IsDelete == false && c.MealGroupCode == mealGroup.MealGroupCode).FirstOrDefault();
if (meal == null)
{
context.MealGroups.Add(mealGroup);
context.SaveChanges();
Return = 1;
}
else
{
meal.MealGroupCode = mealGroup.MealGroupCode;
this.context.Entry(meal).State = EntityState.Modified;
this.context.SaveChanges();
Return = 2;
}
}
catch (Exception ex)
{
Return = 0;
string Type = "Group Meal Details Save";
txt.Exsepotion(Type, ex.ToString());
}
return Return;
}
}
}
here is my another code and this doesnot create the entities of the table as auto .please i need to know what is the reason for this and help me pleas e
I am using MongoVue application to show the data preview stored in "MongoDb".
In the attached image, the database name "Energy" has collection name "DataLog". In "DataLog", there are several rows. I am adding these row to the collection by reading it from a .CSV file.
Now sometimes the column name Pings has huge data [say array of 2000 items] for a single row due to which the exception occurs i.e if "MaxDocumentSize exceeds in 16MB"
Since the Pings array was huge which threw an exception and to avoid this, I removed the collection of Pings [i.e. entered blank collection] from row and tried to Insert, it went successful.
Now I want to update the Pings for the same entry, but in case the array is something like 2000 elements or above, then I wish to update it in group of 500 items [500 x 4 = 2000] in a loop.
Can anyone help me out.
** SAMPLE CODE **
private void InsertData(Datalog xiDatalog)
{
List<Ping> tempPings = new List<Ping>();
tempPings.AddRange(xiDatalog.Pings);
xiDatalog.Pings.RemoveAll(x => x.RowId != 0);
WriteConcernResult wc = mongoCollection.Insert(xiDatalog);
counter++;
var query = new QueryDocument("_id", xiDatalog.Id);
MongoCursor<Datalog> cursor = mongoCollection.FindAs<Datalog>(query);
foreach (Datalog data in cursor)
{
AddPings(data, tempPings, mongoCollection);
break;
}
}
private void AddPings(Datalog xiDatalog, List<Ping> xiPings, MongoCollection<Datalog> mongoCollection)
{
int groupCnt = 0;
int insertCnt = 0;
foreach (Ping px in xiPings)
{
xiDatalog.Pings.Add(px);
groupCnt++;
if (((int)(groupCnt / 500)) > insertCnt)
{
UpdateDataLog(xiDatalog.Id, xiDatalog.Pings, mongoCollection);
insertCnt++;
}
}
}
private bool UpdateDataLog(BsonValue Id, List<Ping> tempPings, MongoCollection<Datalog> mongoCollection)
{
bool success = false;
try
{
var query = new QueryDocument("_id", Id);
var update = Update<Datalog>.Set(e => e.Pings, tempPings);
mongoCollection.Update(query, update);
success = true;
}
catch (Exception ex)
{
string error = ex.Message;
}
return success;
}
Answer : Just modified the code to use Update.PushAll() instead of Update.Set()
Please refer below code
private bool UpdateDataLog(BsonValue Id, List<Ping> tempPings, MongoCollection<Datalog> mongoCollection)
{
bool success = false;
try
{
var query = new QueryDocument("_id", Id);
var update = Update<Datalog>.PushAll(e => e.Pings, tempPings);
mongoCollection.Update(query, update);
success = true;
}
catch (Exception ex)
{
string error = ex.Message;
}
return success;
}