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();
}
}
Related
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.
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 have the following code:
public int DeActivate(User entity) {
try {
using (UsersDataContext usersDC = new UsersDataContext()) {
users user = new users();
user = usersDC.users.Where(x => x.id == entity.Id).
Select(x => new users {active = x.active}).FirstOrDefault();
//user.active = entity.Active;
user.active = false;
usersDC.SubmitChanges();
return 1;
}
}
catch {
return 0;
}
}
While running an NUnit test on the method, the method returns 1, as it is supposed to do, and while de-bugging no exceptions are thrown. But, when i cross check with the DB the records have not being affected. I have tried the following: Re-created DBML file, checked for existance of PK, and checked the following sites:
MSDN question, StackOverflow question, but to no avail.
Your select statement is wrong. Try this.
public int DeActivate(User entity) {
try {
using (UsersDataContext usersDC = new UsersDataContext()) {
var user = usersDC.users.Single(x => x.id == entity.Id);
user.active = false;
usersDC.SubmitChanges();
return 1;
}
} catch {
return 0;
}
}
I'm trying to return a value from a function. The function WcfProvider.MetalsPrices may throw an exception. I want to avoid it.
public IEnumerable<PriceOfMetal> GetPrice(int id, DateTime time)
{
bool condition = false;
DateTime timenew = time.AddDays(-1);
var allPrice = from c in db.PriceOfMetal
select c;
foreach (var i in allPrice)
{
if (i.Date.Date == timenew.Date && i.ListOfMetaL_Id==id)
{
condition = true;
}
}
try
{
if (condition == false)
{
var price = WcfProvider.MetalsPrices(id, time, time).Tables[0].AsEnumerable()
.Select(
a =>
new PriceOfMetal()
{
Date = a.Field<DateTime>("Date"),
ListOfMetaL_Id = a.Field<int>("MetalId"),
Value = a.Field<System.Double>("Price")
})
.ToList().Single();
db.PriceOfMetal.Add(price);
db.SaveChanges();
}
}
finally
{
var all = from c in db.PriceOfMetal select c;
return all;
}
I want to return the value of the block finally. Is it possible? I get an error.
You have to decide whether your function should return normally or abnormally if an exception occurs inside.
If abnormally (your caller will see the exception):
try {
// do stuff
return answer;
}
finally {
// cleanup stuff
}
If normally, you need to handle the exception:
try {
// do stuff
}
catch {
// recover stuff
}
// cleanup stuff
return answer;
You can never put a return statement in a finally block, because finally runs when there is an uncaught exception, and when your function ends (abnormally) due to uncaught exception, there is no return value.
you may need a pattern like this
try
{
return here
}
catch(Exception ex)
{
// Catch any error
// re throw if you choose,
// or you can return if you choose
return here
}
finally
{
// allways do whats here
}
You might want to read a couple of the pages around here : try-catch-finally (C# Reference)
Just to build on this a bit more, Imagine if we could return within a finally block
You could have a nasty piece of code like below, which would be confusing at best
try
{
return 10;
}
catch (Exception e)
{
return 20;
}
finally
{
return 30;
}
What would the compiler return?
I'm sorry to say this but your question is vague and hard to answer. Your code looks over complicated. Anyway it's holiday time. Maybe below will help you along. No guarantees though.
public IEnumerable<PriceOfMetal> GetPrice(int id, DateTime time)
{
DateTime timenew = time.AddDays(-1);
var allPrice = from c in db.PriceOfMetal
select c;
where c.Date.Date == timenew.Date
and c.ListOfMetal_Id == id
if (!allPrice.Any())
{
try
{
var price = WcfProvider.MetalsPrices(id, time, time).Tables[0].AsEnumerable()
.Select(a =>new PriceOfMetal
{
Date = a.Field<DateTime>("Date"),
ListOfMetaL_Id = a.Field<int>("MetalId"),
Value = a.Field<System.Double>("Price")
})
.ToList().Single();
db.PriceOfMetal.Add(price);
db.SaveChanges();
}
catch
{
// Eating exceptions like this is really poor. You should improve the design.
}
}
return db.PriceOfMetal;
}
-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();
}
}