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
}
}
Related
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;
}
}
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'm trying to get all emails (to, from, cc) from an email in a list and go through the list and check the contacts, if the Contact exists in CRM then a field on the email entity will be marked as true. When I check the to, from, and cc fields of the email it returns 0 parties, but there is no error there. Also at the end, when I'm calling service.Update(entity), it returns an error. An unexpected error occurred.
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider
.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider
.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = factory
.CreateOrganizationService(context.UserId);
try
{
Email entity;
if (context.MessageName == "Create")
{
if (context.PostEntityImages.Contains("PostImage")
&& context.PostEntityImages["PostImage"] is Entity)
entity = (Email)context.PostEntityImages["PostImage"].ToEntity<Email>();
else
throw new Exception("No PostEntityImages...");
}
else
throw new Exception("EmailPortalVisibilityPlugin Plugin invalid");
if(entity.LogicalName != "email")
throw new Exception("EmailPortalVisibilityPlugin invalid");
bool contactExists = false;
List<string> emails = new List<string>();
emails.AddRange(ParseAddressUsed(entity.To, trace));
emails.AddRange(ParseAddressUsed(entity.From, trace));
emails.AddRange(ParseAddressUsed(entity.Cc, trace));
foreach (String em in emails)
{
contactExists = LookupContact(em, service, trace);
if (contactExists)
break;
}
UpdateToggleState(entity, contactExists, service, trace);
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException("Execute '" + ex.Message + "'");
}
}
public List<string> ParseAddressUsed(
IEnumerable<ActivityParty> entity, ITracingService trace)
{
try
{
List<string> addressStrings = new List<string>();
foreach (ActivityParty party in entity)
addressStrings.Add(party.PartyId.Id.ToString());
return addressStrings;
}
catch (FaultException<OrganizationServiceFault> exceptionServiceCall)
{
throw new Exception("ParseAddressUsed FaultException");
}
catch (Exception ex)
{
throw new Exception("ParseAddressUsed Exception");
}
}
public bool LookupContact(
String emailAddress, IOrganizationService service, ITracingService trace)
{
try
{
QueryByAttribute queryByAttribute = new QueryByAttribute("contact");
queryByAttribute.ColumnSet = new ColumnSet("contactId");
queryByAttribute.Attributes.Add("emailaddress1");
queryByAttribute.Values.Add(emailAddress);
EntityCollection retrieved = service.RetrieveMultiple(queryByAttribute);
return (retrieved.Entities.Count > 0);
}
catch (FaultException<OrganizationServiceFault> exceptionServiceCall)
{
throw new Exception("LookupContact Exception");
}
catch (Exception ex)
{
throw new Exception("LookupContact Exception");
}
}
public void UpdateToggleState(
Email entity, bool toggleState, IOrganizationService service, ITracingService trace)
{
try
{
Entity email = new Entity("email");
email.Id = entity.Id;
email.Attributes.Add("new_clientfacing", toggleState);
service.Update(email);
}
catch (FaultException<OrganizationServiceFault> exceptionServiceCall)
{
throw new Exception("UpdateToggleState Exception");
}
catch (Exception ex)
{
throw new Exception("UpdateToggleState Exception");
}
}
Try to set the first argument type of function ParseAddressUsed to EntityCollection instead of IEnumerable<ActivityParty>, and do the necessary changes.
And for the final update in function UpdateToggleState, there is no need to create a new email Entity (Entity email = new Entity("email");), when you already have the entity variable. You could just set the new_clientfacing attribute and update the entity, which is already retrieved.
In your method ParseAddressUsed you are adding the PartyId GUID to the string list and you use it in LookupContact in the emailaddress1 filter as a parameters, that is probably the reason why you are not retrieving any records.
Please try to change addressStrings.Add(party.PartyId.Id.ToString()) to addressStrings.Add(party.AddressUsed) instead and see if that works.
Cheers, dimamura
God day!
I have a tree of entities and at specific point of time i need to update only scalar properties of one entity. Classic update rise entire graph lookup, but relations not need to update.
The trouble in Category entity what one category have another categories in children. My method generate exceptions when saving changes about duplicate key. I think EF try to add children to database.
Static method of my data context listed below:
public static void Update<T>(T item) where T : KeyedObject
{
if (item == null)
throw new ArgumentNullException("Item to update is null");
item.ValidateIsNotNew();
using (DataContext db = new DataContext())
{
T original = GetOriginalWithException<T>(db, item);
DbEntityEntry entry = db.Entry(original);
entry.CurrentValues.SetValues(item);
entry.State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (Exception ex)
{
throw new DatabaseException(
"Cant update list item. See inner exception for details.",
ex);
}
}
}
I tries another method: attaching object. This method does not throw exception, but it rise entire graph update and take many resources. Code listed below:
public static void Update<T>(T item) where T : KeyedObject
{
if (item == null)
throw new ArgumentNullException("Item to update is null");
item.ValidateIsNotNew();
using (DataContext db = new DataContext())
{
db.Set<T>().Attach(item);
db.Entry(item).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (Exception ex)
{
throw new DatabaseException(
"Cant update list item. See inner exception for details.",
ex);
}
}
}
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.