I want to do something like when user click a button then it will remove data from database ( it will only have one data every time user run the system). the problem is I try to use this code to remove the data but it does not work.
public void RemoveOrder(Order order)
{
try
{
using (tempPosOrderPaymentDBContext db = new tempPosOrderPaymentDBContext ())
{
db.Orders.Remove(order);
db.SaveChanges();
}
}
catch (Exception ex)
{
CustomExceptionHandling customExceptionHandling = new CustomExceptionHandling();
customExceptionHandling.CustomExHandling(ex.ToString());
}
}
when I try to add the data to database using the same code but only change the remove to Add it working fine. but only with this remove thing it does not work.
Can you try this and it should work:
public void RemoveOrder(Order order)
{
try
{
using (tempPosOrderPaymentDBContext db = new tempPosOrderPaymentDBContext ())
{
var orderInDb = db.Orders.First(x=> x.OrderId == order.OrderId);
db.Orders.Remove(orderInDb);
db.SaveChanges();
}
}
catch (Exception ex)
{
CustomExceptionHandling customExceptionHandling = new CustomExceptionHandling();
customExceptionHandling.CustomExHandling(ex.ToString());
}
}
Related
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
I want to populate state and city according to country selected .I have done this but now I want to create this with stored Procedure and with class file .. Can someone please help ?
Here is a Sample Prcedure to create a Dropdown of Language:
SP
CREATE proc sp_getlangusges
as
select LanguageId,Languages from Languages
CS
public DataSet Getalllanguages()
{
try
{
// you loginc to connect to database using sp
}
catch (Exception ex)
{
throw ex;
}
}
In Aspx.cs
Classfinename objEvents = new Classfinename ();
private void BindContrydropdown()
{
try
{
DataSet dsLang = objEvents.Getalllanguages();
if (dsLang.Tables[0].Rows.Count > 0)
{
ddllang.DataTextField = "Languages";
ddllang.DataValueField = "LanguageId";
ddllang.Items.Clear();
ddllang.DataSource = dsLang;
ddllang.DataBind();
ddllang.Items.Insert(0, new ListItem("Please Select"));
}
}
catch (Exception ex)
{ }
}
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
}
I use following script to get data from external service and store in dB. In certain rare cases less than 1% records gets updated with null values. In below code, the "re.status=fail" we see null. let us know if any thots.
public void ProcessEnquiries()
{
List<req> request = new List<req>();
var options = new ParallelOptions { MaxDegreeOfParallelism = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["MaxDegreeOfParallelism"]) };
try
{
Parallel.ForEach(request, options, currentRequest =>
{
ProcessedRequest processedRequest = null;
processedRequest = CommunicateToWS(currentRequest); // Here we call to webservice
});
}
catch (AggregateException exception)
{
foreach (Exception ex in exception.InnerExceptions)
{
// Handle Exception
}
}
}
public ProcessedRequest CommunicateToWS(req objReq)
{
ProcessedRequest re = new ProcessedRequest();
using (WebCall obj = new WebCall())
{
re.no = refnu;
try
{
retval = obj.getValue(inval);
objProxy.Close();
//get data
// parse and store to DB
}
catch (Exception e)
{
re.status = "fail";
//update DB that request has failed
//Handle Exception
obj.Close();
}
}
}
I have SQLite database in isolated storage in Windows Store App.
I use SQLite for Windows Runtime
When i want to delete all table entry I use follow method:
public static async void DeleteAllProjects()
{
var storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync("myDb.sqlite");
using (var db = new SQLiteConnection(storageFile.Path))
{
try
{
db.DeleteAll<Projects>();
}
catch
(Exception ex)
{
Debug.WriteLine("Delete error " + ex.Message);
}
}
}
All work like a charm.
But when i need to delete part of entries:
public static async void Delete(List<Projects> projects)
{
var storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync("myDb.sqlite");
using (var db = new SQLiteConnection(storageFile.Path))
{
try
{
foreach (var project in projects)
{
var existingProject = (db.Table<Projects>().Where(
p => p.id == project.Id)).FirstOrDefault();
if (existingProject != null)
{
db.Delete<Projects>(existingProject);
}
}
}
catch
(Exception ex)
{
Debug.WriteLine("Delete error " + ex.Message);
}
}
}
I handled exeption with
ex.Message = "Cannot delete Projects: it has no PK" string
Can somebody help me?