I have this method :
public void Update(DBS.BankAccount entity)
{
try
{
using (var _nahidContext = new NahidContext())
{
_nahidContext.BankAccounts.Attach(entity);
var bankAccountElement = _nahidContext.Entry(entity);
bankAccountElement.CurrentValues.SetValues(entity);
_nahidContext.SaveChanges();
//__________ or ___________
//var bankAccountElement = FindById(entity.Id);
//if (_nahidContext.Entry(bankAccountElement).State == System.Data.Entity.EntityState.Detached)
//{
// _nahidContext.BankAccounts.Attach(bankAccountElement);
//}
////_nahidContext.Entry(bankAccountElement).State = System.Data.Entity.EntityState.Modified;
//_nahidContext.SaveChanges();
}
}
catch (Exception ex)
{
throw new ArgumentException(ex.Message);
}
}
Which run without any error but my bankAccountElement does not change.
Please help me.
First you attach (entity state= unchanged), then you set values with same values than attached entity, so it keeps unchanged.
You should do this
_nahidContext.BankAccounts.Attach(entity);
var bankAccountElement = _nahidContext.Entry(entity);
bankAccountElement.State = EntityState.Modified;
You can read more here
Related
I have a android app created with xamarin.
This is the code that crashes, not the first time, but often on the second time!
public void InsertOrUpdateInventoryWithoutEntries(Inventory inventory)
{
_logger.Debug("Enter");
try
{
var db = _dataBaseConnection.GetSqLiteConnection();
using (db)
{
var existingDbInventory = db.Find<DbInventory>(dbInventory => dbInventory.Code ==
inventory.Code);
if (existingDbInventory != null)
{
if (!existingDbInventory.Finished ) // do not update if finished.
{
existingDbInventory.Description = inventory.Description;
existingDbInventory.OpenTime = inventory.OpenTime;
existingDbInventory.Finished = inventory.Finished ;
existingDbInventory.UseInventoryList = inventory.UseInventoryList;
existingDbInventory.PostedToServer = inventory.PostedToServer;
existingDbInventory.InventoryListIsDownloaded =
inventory.InventoryListIsDownloaded;
UpdateInventory(existingDbInventory,db);
}
}
else
{
db.Insert(DbInventory.FromInventory(inventory));
}
db.Close();
}
}
catch
(SQLiteException ex)
{
_logger.Error(ex);
throw;
}
}
private void UpdateInventory(DbInventory inventory, SQLiteConnection db)
{
_logger.Debug("Enter");
try
{
var result = db.Update(inventory);
}
catch (SQLiteException ex)
{
_logger.Error(ex);
throw;
}
}
public bool InsertOrUpdateInventoryEntry(InventoryEntry inventoryEntryModel,
SQLiteConnection db=null)
{
_logger.Debug("Enter");
bool disposeFlg = false;
//detta då sqllite inte klarar av samtidiga anrop så bra, så man skall bara använda en
connection i taget !
if (db == null)
{
db = _dataBaseConnection.GetSqLiteConnection();
disposeFlg = true;
}
var existingDbInvetoryRow = db.Find<DbInventoryEntry>(dbInventoryRow =>
dbInventoryRow.ItemId == inventoryEntryModel.ItemId && dbInventoryRow.InventoryCode ==
inventoryEntryModel.InventoryCode);
if (existingDbInvetoryRow != null)
{
existingDbInvetoryRow.Cost = inventoryEntryModel.Cost;
existingDbInvetoryRow.Quantity = inventoryEntryModel.Quantity;
db.Update(existingDbInvetoryRow);
}
else
{
db.Insert(DbInventoryEntry.FromInventoryEntry(inventoryEntryModel));
}
if (disposeFlg)
{
db.Close();
db.Dispose();
}
return true;
}
private bool InsertInventoryRows(IEnumerable<InventoryEntry> inventoryEntryModels)
{
_logger.Debug("Enter");
var dbRows = inventoryEntryModels.Select(entry =>
(DbInventoryEntry.FromInventoryEntry(entry)));
var db = _dataBaseConnection.GetSqLiteConnection();
using (db)
{
db.InsertAll(dbRows);
db.Close();
}
return true;
}
The error I get is:
SQLite.SQLiteException: 'database is locked' or SQLite.SQLiteException: 'database is busy'
I found the solution thanks to Jason - github.com/praeclarum/sqlite-net/issues/700
I would advise you to keep a single SQLiteConnection for your app and cache it to take advantage of the type mapping caching strategy. Opening it with the Create | ReadWrite | FullMutex flags will ensure all operations are multithread-wise serialized. Don't forget to Dispose the connection whenever your app closes
This worked perfectly and speeded up the app ! Thanks Jason !
What i did was to handle one static connection that i held open all the time !
I'm baffled on this one. Nothing returns from context.SaveChanges() it never goes to the catch it never finishes and the variable r never gets assigned a value.
How can I find out what the error is?
public void DeleteStuff(int stuffID)
{
using (var context = new MYConn())
{
var user = new MY_STUFF { STUFF_ID = stuffID};
var entry = context.Entry(user);
if (entry.State == EntityState.Detached)
{
context.MY_STUFF.Attach(user);
}
context.MY_STUFF.Remove(user);
try
{
var r = context.SaveChanges();
}
catch (Exception ex)
{
string a = ex.Message;
}
}
}
As Octanic suggested, after I put a sniffer on I realized I had a deadlock.
My code to use the function for updating is here and it works also
[HttpPost]
public bool SaveDefCompny(DefCompanyDTO DefCmpny)
{
using (RPDBEntities db = new RPDBEntities())
{
using (TransactionScope trans = new TransactionScope())
{
//the problem is here incase of saving
var UpdateDefCmpnyId = (from CmpnyId in db.DefCompanies
where CmpnyId.Id == DefCmpny.Id
select CmpnyId).First();
List<DefCompany> list = new List<DefCompany>();
list.Add(UpdateDefCmpnyId);
try
{
foreach (DefCompany DefCmpny1 in list)
{
DefCmpny1.Id = DefCmpny1.Id;
DefCmpny1.ShortName = DefCmpny.ShortName;
DefCmpny1.FullName = DefCmpny.FullName;
DefCmpny1.ContactPerson = DefCmpny.ContactPerson;
DefCmpny1.Address1 = DefCmpny.Address1;
DefCmpny1.CompanyCity = DefCmpny.CompanyCity;
DefCmpny1.CompanyState = DefCmpny.CompanyState;
DefCmpny1.CompanyCountry = DefCmpny.CompanyCountry;
DefCmpny1.ZipPostCode = DefCmpny.ZipPostCode;
DefCmpny1.TelArea = DefCmpny.TelArea;
DefCmpny1.CurrentCurrencyCode = DefCmpny.CurrentCurrencyCode;
db.SaveChanges();
trans.Complete();
}
}
catch (Exception ex)
{
}
}
return false;
}
}
when I try to save instead of updating the line of code
var UpdateDefCmpnyId = (from CmpnyId in db.DefCompanies
where CmpnyId.Id == DefCmpny.Id
select CmpnyId).First();
gives null value and hence saving fails because record is new and not present in database so how to handle null in case of saving how to use try catch so that when value is null it proceed to saving code that add
How about something along these lines:
var UpdateDefCmpnyId = (from CmpnyId in db.DefCompanies
where CmpnyId.Id == DefCmpny.Id
select CmpnyId).FirstOrDefault();
if(UpdateDefCmpnyId == null)
{
//insert
//(handle the id however you need to for insert. depending on your setup, you might be able to leave it empty and let the database put it in for you)
}
else
{
//update
//set the id as you do in the question
}
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