Reputation: 769
I have a database table and I'm trying to update a cell with a money datatype (decimal) and I'm using LINQ and and Entity Framework.
Unfortunately Context.SaveChanges();
won't work for some reason.
Here is the table structure
Type Amount Machine
Cash 1000 Tablet
Here is my code:
using (var GC = new GroundCommanderEntities())
{
PAYMENT_Repo PAYMENTREPO = new PAYMENT_Repo();
var ExistingCashPayment = GC.PAYMENT_Repo
.Where(Filter => Filter.Type == "Cash" && Filter.Machine == "Tablet").ToList();
string type = "";
var amt = 0.00m;
foreach (var item in ExistingCashPayment)
{
type = item.Type;
amt = item.Amount;
}
if (type == cbPaymentType.Text) //a combobox that contains Types
{
PAYMENTREPO.Amount = amt + Convert.ToDecimal(txtTendering.Text);
GC.SaveChanges();
return true;
}
else
{
return false;
}
}
Upvotes: 1
Views: 687
Reputation: 21
It looks like GC is your DbContext. If so you need to add the state of the object is modified as follows...
db.Entry(obj).State = System.Data.Entity.EntityState.Modified; db.SaveChanges();
This should work.
Upvotes: 2
Reputation: 41539
There are a couple of problems here:
Most importantly, PAYMENTREPO
is a new instance - its not from the db context, so changing values on it has no effect. You need to add it before saving changes:
PAYMENTREPO.Amount = amt + Convert.ToDecimal(txtTendering.Text);
GC.PAYMENTREPOs.Add(PAYMENTREPO);
GC.SaveChanges();
Second, which won't cause the complete fail to update, but will cause the code to do things other than you expect:
foreach (var item in ExistingCashPayment)
{
type = item.Type;
amt = item.Amount;
}
This loop will leave type
and amt
set to the last value in the ExistingCashPayment list, rather than some sort of accumulation of the contents of that list, which would be the desired behaviour implied by having the loop there in the first place.
Upvotes: 1
Reputation: 754220
When you create a new entity like you do, you must add it to the context before calling SaveChanges()
:
using (var GC = new GroundCommanderEntities())
{
PAYMENT_Repo PAYMENTREPO = new PAYMENT_Repo();
var ExistingCashPayment = GC.PAYMENT_Repo
.Where(Filter => Filter.Type == "Cash" && Filter.Machine == "Tablet").ToList();
string type = "";
var amt = 0.00m;
foreach (var item in ExistingCashPayment)
{
type = item.Type;
amt = item.Amount;
}
if (type == cbPaymentType.Text) //a combobox that contains Types
{
PAYMENTREPO.Amount = amt + Convert.ToDecimal(txtTendering.Text);
// add your NEW entity to the context!
// depending on which exact version of EF you're using, this
// might be called `.Add()` or `.AddObject()`
// Also, the name "PAYMENTREPOs" is just a guess - it might be
// different in your concrete case - adapt as needed!
GC.PAYMENTREPOs.Add(PAYMENTREPO);
GC.SaveChanges();
return true;
}
else
{
return false;
}
}
Upvotes: 1