When I am trying to insert some value using this code I am getting the error below:
{"ORA-00001: unique constraint (NCOREDB.PK_NCORE_CASH_IN) violated"}
I am using EF5 and Oracle as Database.It was working fine a while ago. I can not update my EF because of some dependency issue.
using (TransactionScope transactionScope = new TransactionScope())
{
try
{
NCORE_TRN_CASH_IN_INFO OBJ_NCORE_TRN_CASH_IN_INFO = new NCORE_TRN_CASH_IN_INFO();
int id = Convert.ToInt32(Obj_nCoreEntities.NCORE_TRN_CASH_IN_INFO.Max(t => (int?)t.CASH_IN_ID)) + 1;
OBJ_NCORE_TRN_CASH_IN_INFO.CASH_IN_ID = id;
//Inserting other value here
Obj_nCoreEntities.NCORE_TRN_CASH_IN_INFO.Add(OBJ_NCORE_TRN_CASH_IN_INFO);
Obj_nCoreEntities.SaveChanges();
transactionScope.Complete();
}
catch (DbEntityValidationException dbEx)
{
transactionScope.Dispose();
string inner = ExceptionExtendedMethods.GetDBInnerExceptions(dbEx);
return inner;
}
catch (Exception ex)
{
transactionScope.Dispose();
string inner4 = ExceptionExtendedMethods.GetInnerExceptions(ex);
return inner4;
}
}
Related
I have company table where values are inserted
public int SaveCompany(Company objCompany)
{
int CompanyID = 0
try
{
using (var context = new Cubicle_EntityEntities())
{
context.Companies.Add(objCompany); //add entity to the add method
int res = context.SaveChanges(); //insert it into table
if (res > 0)
{
Debug.WriteLine("Data Inserted Successfully");
}
else
{
Debug.WriteLine("Try Again");
}
CompanyID = objCompany.CompanyId;
Debug.WriteLine("CompanyId " + CompanyID);
}
}
catch (Exception ex)
{
CompanyID = 0;
bool rethrow = UserInterfaceExceptionHandler.HandleException(ref ex);
throw ex;
}
return CompanyID;
}
Every time I get res 1,but data not inserted in table.
I am having a problem with repeating previous operations when there is an error in the SaveChanges method of Entity Framework.
Below is the code block
public static int SaveChangesTask(this DbContext db)
{
int result = -1;int countLoop = 0;
bool continueLoop = true;
var modifiedOrAddedEntities = db.ChangeTracker.Entries().Where(a => a.State != EntityState.Detached
&& a.State != EntityState.Unchanged).ToList();
while (continueLoop && countLoop<3)
{
try
{
result= db.SaveChanges();
continueLoop = false;
}
catch(Exception ex)
{
string error = ex.ToSystemException();
if(error.ToLowerInvariant().Contains("ORA-00060".ToLowerInvariant()) || error.ToLowerInvariant().Contains("deadlock"))
{
foreach (var item in modifiedOrAddedEntities)
{
db.Entry(item).State = item.State;
}
countLoop++;
Random rnd = new Random();
System.Threading.Thread.Sleep(rnd.Next(1, 5)* 1000);
}
else
{
throw ex;
}
}
}
return result;
}
But when I want to add old tracking objects to context, Entity Framework Throws Exception like that
"The entity type DbEntityEntry is not part of the model for the current context"
How to catch the RAISEERROR or SQL 2012 - THROW exception from sql store procedure to entity framework - store procedure call ?
using (Entities context = new Entities())
{
IEnumerable<EmployeeDetails> empDetails = context. Database.SqlQuery
< EmployeeDetails >("exec GetEmployeeData ", null).ToList();
}
Try / Catch?
using (Entities context = new Entities())
{
try
{
IEnumerable<EmployeeDetails> empDetails = context. Database.SqlQuery <EmployeeDetails>("exec GetEmployeeData ", null).ToList();
}
Catch (SqlException ex)
{
//Do something
}
}
I added some entities to my context.And then i migrate them as a below with my tool
using (var db = new TourismContext())
{
if (db.Database.CompatibleWithModel(true))
return;
var initializer = new MigrateDatabaseToLatestVersion<TourismContext, TourismContextConfiguration>();
initializer.InitializeDatabase(db);
//and other code.....
it drop tables which i removed them from my context.And it works.it is compatible.But after 20 minutes it says non compatible.it want to drop some tables but this tables are not existing
what should i do?
although i remove that tables from context and migrate it(migration tool drop that tables from database) why it want to drop them again and again?the tables that migration want to drop is not existing in database.because i migrate them so migration tool drop them.Where migration get that tables info to drop?
this is my __MigrationHistory
SELECT TOP 1000 [MigrationId]
,[Model]
,[ProductVersion]
,[CreatedOn]
FROM [TOURISM_new1].[dbo].[__MigrationHistory]
there is no droping tables info here
here is my migration tool.There is two buton.one show scritp which will show executed script(script button) other is micration buton.it migrate
private void MigrateButton_Click(object sender, EventArgs e)
{
try
{
using (var db = new TourismContext())
{
if (db.Database.CompatibleWithModel(true))
return;
var initializer = new MigrateDatabaseToLatestVersion<TourismContext, TourismContextConfiguration>();
initializer.InitializeDatabase(db);
foreach (Constants.SecurityFeatureIdentifier securityFeatureIdentifier in Enum.GetValues(typeof(Constants.SecurityFeatureIdentifier)))
{
if (db.SecurityFeatures.All(sf => sf.SecurityFeatureIdentifierID != (int)securityFeatureIdentifier))
{
db.SecurityFeatures.Add(new SecurityFeature { SecurityFeatureIdentifier = securityFeatureIdentifier });
db.SaveChanges();
}
}
}
statusLabel.Text = "Compatible";
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void ScriptButton_Click(object sender, EventArgs e)
{
try
{
using (var db = new TourismContext())
{
if (db.Database.CompatibleWithModel(true))
return;
var migrator = new DbMigrator(new TourismContextConfiguration());
var scriptor = new MigratorScriptingDecorator(migrator);
scriptControl.Text = scriptor.ScriptUpdate(null, null);
foreach (Constants.SecurityFeatureIdentifier securityFeatureIdentifier in Enum.GetValues(typeof(Constants.SecurityFeatureIdentifier)))
{
if (db.SecurityFeatures.All(sf => sf.SecurityFeatureIdentifierID != (int)securityFeatureIdentifier))
{
db.SecurityFeatures.Add(new SecurityFeature { SecurityFeatureIdentifier = securityFeatureIdentifier });
db.SaveChanges();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
You need to get your database model in sync with your code first model. You could either comment out the obsolete code from the Up() method of the migration and do an update-database or you can remove the pending migration and do Add-Migration MyBaseline –IgnoreChanges with an update-database. Now you should be compatible until you change your model.
https://msdn.microsoft.com/en-us/data/dn579398.aspx?f=255&MSPPError=-2147217396#option1
I am developing an MVC app.
When I try to updated record it showing error of DBEntityValidation exception,
( beacuse its trying to add record in DB. This is my code)
public JsonResult SavePassword(int EmpId, string Password)
{
try
{
Employee e1 = db.Employees.First(i => i.Id == EmpId);
db.Entry(e1).State = EntityState.Modified;
e1.Password = Password;
db.SaveChanges();
return Json(EmpId);
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
}
In exception, it shows that validation msgs, which I have checked while adding new record.
So , I think its trying to add in DB insted of updating.