Add data in to database asp.net - c#

I want to add data into database and I get this error.
An exception of type 'System.Data.Entity.Core.EntityException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: An error occurred while starting a transaction on the provider connection. See the inner exception for details.
Here is my code.
public void alarmlog(int id)
{
AlarmLog log = new AlarmLog();
if (id == 1)
{
log.SectorID = "LRD";
log.LineNo = "L01";
log.WorkStation = "02";
log.LMQS = 1;
log.StaffID = 6;
log.DateTime = DateTime.Now;
}
db.AlarmLogs.Add(log);
db.SaveChanges();
}

I have a hunch, that your error is located at your if(id==1) statement. My guess is, that you pass in an id which is not 1. A new Alarmlog is created, the if statement does not return true and then you attempt to add an empty Item to the database.
If all those fields, even one for that matter, may not be null, an exception does get thrown.
Remove your if-block and see if the error has vanished:
public void alarmlog(int id)
{
AlarmLog log = new AlarmLog();
log.SectorID = "LRD";
log.LineNo = "L01";
log.WorkStation = "02";
log.LMQS = 1;
log.StaffID = 6;
log.DateTime = DateTime.Now;
db.AlarmLogs.Add(log);
db.SaveChanges();
}
If you want us to stop guessing, please do what the commenters said: wrap your code in try { ... } catch(Exception ex) { ... } blocks to see what the error is.

Related

Perform Insert or Update at same time

I am trying to perform a simple insert or update command in EF 6 but as the method is being called twice (as I want to update different fields each time) EF hasn't completed the INSERT in time for the second call to think it too needs to perform an INSERT.
Below is how I attempted to catch the error and retry with an Update
Simplified:
try{
var record = new DBRecord(){
id = 1234,
token1 = shouldUpdateToken1 ? "OK" : null,
token2 = shouldUpdateToken1 ? null : "OK"
}
dbContext.entityTable.Attach(record).State = dbContext.entityTable.Any(x => x.id == 1234) ? EntityState.Modified ? EntityState.Added;
dbContext.SaveChanges();
} catch (Exception ex)
{
// Must require update
dbContext.ChangeTracker.Clear();
// Only create object with fields to change otherwise it will overwrite existing
var newRecord = new DBRecord(){
}
id = 1234
};
if ( shouldUpdateToken1 ){
newRecord.token1 = "OK";
dbContext.entityTable.Attach(newRecord).Property(x => x.token1).IsModified = true;
} else {
newRecord.token2 = "OK";
dbContext.entityTable.Attach(newRecord).Property(x => x.token2).IsModified = true;
}
dbContext.SaveChanges();
}
Is this really the best solution ? The try catch block is allowing me to react to the primary key violation (id is the PK) as it errors with:
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
---> MySqlConnector.MySqlException (0x80004005): Duplicate entry '1234' for key 'PRIMARY'
This is obviously because the inert is being attempted for both runs of this method.
I believe EF 7 has some improvements for Upsert commands but I'm locked to 6.12.

Why is a duplicate key error being thrown and value still inserted

A document is inserted into a collection using c#
{
"_id" : UUID("some_guid")
}
Via
db.collection.insert(new { id = a_guid });
We rely upon the uniqueness of the guid/uuid by specifying the id in the document meaning the mongo db driver is spared from doing this.
Now, all of this is wrapped in a try..catch where a duplicate key exception is caught. Calling code uses this routine for conflict checking. That is, if a guid hasnt been encountered before - insert it - next time around and on trying to insert the same value again, the exception lets us now there's a duplicate.
We appear to be getting into a situation where values are written but an exception is STILL thrown, indicating a conflict where there isnt one.
We have had this working in a 3 node replica set.
It is NOT working in a 5 node replica set, purporting to be healthy. The write concern is set to 1, indicating acknowledgement when the master is written to (but not the journal) just like the 3 node set.
Where should I dig deeper? The duplicate exception derives from a writeconcern exception, is something screwy going on here? Is the mongo driver correctly interpreting the error and raising the right exception?
Any leads would be great!
EDIT:
var database = this.client.GetServer().GetDatabase("A_Database");
var collection = database.GetCollection<object>("A_Collection");
try
{
collection.Insert(new { Id = paymentReference.ToGuid() });
}
catch (MongoDuplicateKeyException)
{
return false;
}
return true;
This is NOT called in a loop.
You can catch the exception base MongoWriteException and filter with when by the Category, example code:
var database = this.client.GetServer().GetDatabase("A_Database");
var collection = database.GetCollection<object>("A_Collection");
try
{
collection.Insert(new { Id = paymentReference.ToGuid() });
}
catch (MongoWriteException ex) when(ex.WriteError.Category == ServerErrorCategory.DuplicateKey)
{
return false;
}
return true;
Hear's a fixed version of your code
var database = this.client.GetServer().GetDatabase("A_Database");
var collection = database.GetCollection<object>("A_Collection");
try
{
collection.Insert(new { Id = paymentReference.ToGuid() });
}
catch (Exception)
{
collection.Insert(new { Id = Guid.NewGuid(); });
return tru;
}
return true;

intermittent System.Data.Entity.Infrastructure.DbUpdateConcurrencyException

The following code is causing an intermittent exception:
public int UnblockJob(int jobId)
{
using (var connect = MakeConnect())
{
var tag = connect.JobTag.SingleOrDefault(jt => jt.JobId == jobId && jt.Name == Metrics.TagNameItemBlockCaller);
if (tag == null)
{
return 0;
}
connect.JobTag.Remove(tag);
return connect.SaveChanges();
}
}
How can I correct or troubleshoot it?
From the documentation for DbUpdateConcurrencyException:
Exception thrown by DbContext when it was expected that SaveChanges for an entity would result in a database update but in fact no rows in the database were affected.
This means that the record you are attempting to delete has since been removed from the database. It would appear that you have another process that is deleting records or this function is able to be called concurrently.
There are several solutions, here are a couple:
Fix the source problem Stop other processes affecting the data.
Catch the error Wrap this method in a try/catch block, after all you may only care that the record has been deleted:
try
{
//Existing code here
}
catch(DbUpdateConcurrencyException)
{
//Safely ignore this exception
}
catch(Exception e)
{
//Something else has occurred
throw;
}

context.SaveChanges() gives error upon Adding

Using this code I get no errors
public static void kirisekle(string kirisadi, int genislik, int derinlik, int uzunluk, int katid)
{
Beam newbeam = new Beam { Kirisadi = kirisadi, Genişlik = genislik, Derinlik = derinlik, Uzunluk = uzunluk, KatID = katid };
using (pehkEntities context = new pehkEntities())
{
context.Beams.Add(newbeam);
context.SaveChanges();
}
}
However, I get "dbupdateexception was unhandled" error while using this code
public static void dosemeekle(string dosemeadi, int en, int boy, int kalinlik, int katid)
{
Slab newslab = new Slab { DosemeAdi = dosemeadi, En = en, Boy = boy, Kalınlık = kalinlik, KatID = katid };
using (pehkEntities context = new pehkEntities())
{
context.Slabs.Add(newslab);
context.SaveChanges();
}
}
How should I find the reason for this error and fix it?
I am using this code to see the inner exception:
context.Slabs.Add(newslab);
try
{
context.SaveChanges();
}
catch( System.Data.Entity.Infrastructure.DbUpdateException ex)
{
MessageBox.Show(ex.InnerException.Message);
}
However, it shows a messagebox says "an error occured updating the entries. See the inner exception for details." only.
Try to have a look at your table definition in SQL:
are all non-null fields provided in code?
when exception happen is the length of string exceeded
are you using primary key, which already exists in database?
These are most likely reasons for exception if there are no connection issues. I am assuming so since the first method works.

Comparing, Adding, and Updating date field in an entity

Trying to compare an existing date from an entity with current date. If entity field (testfield) of entity (testentity) date is equal to OR after current date, then add 1 year to the date in the field.
Issue - For some reason, its reading all the dates and comparing as well but not updating it in the field. I have used post operation step on the entity.
Update: I added ServiceContext.UpdateObject(entity) and ServiceContext.SaveChanges(); to the code but now its giving me "The context is not currently tracking..." error.
Any help would be deeply appreciated. Thanks!
Please take a look at following code.
public class PostUpdate: Plugin
{
public PostUpdate()
: base(typeof(PostUpdate))
{
base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(40, "Update", "new_testentity", new Action<LocalPluginContext>(ExecutePostUpdate)));
protected void ExecutePostupdate(LocalPluginContext localContext)
{
// get the plugin context
IPluginExecutionContext context = localContext.PluginExecutionContext;
//Get the IOrganizationService
IOrganizationService service = localContext.OrganizationService;
//create the service context
var ServiceContext = new OrganizationServiceContext(service);
ITracingService tracingService = localContext.TracingService;
// The InputParameters collection contains all the data passed in the message request.
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parmameters.
Entity entity = (Entity)context.InputParameters["Target"];
// Verify that the target entity represents an account.
// If not, this plug-in was not registered correctly.
if (entity.LogicalName != "new_testentity")
return;
try
{
var k = entity["new_testfield"];
DateTime m = Convert.ToDateTime(k);
DateTime d = DateTime.Now;
int result = DateTime.Compare(m, d);
// compare the dates
if (result <= 0)
{
try
{
entity["new_testfield"] = DateTime.Now.AddYears(1);
ServiceContext.UpdateObject(entity);
}
ServiceContext.SaveChanges();
//Adding this is giving me "The context is not currently tracking the 'new_testentity' entity."
}
catch (FaultException<OrganizationServiceFault> ex)
{
}
}
}
//<snippetFollowupPlugin3>
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("An error occurred in the FollupupPlugin plug-in.", ex);
}
//</snippetFollowupPlugin3>
catch (Exception ex)
{
tracingService.Trace("FollowupPlugin: {0}", ex.ToString());
throw;
}
}
}
You should register your plugin on the pre-operation step then simply add/change the appropriate value in the InputParameter PropertyBag. That way your changes are inline with the transaction and you don't need a separate update call.
Try attaching your entity to the serviceContext.
http://msdn.microsoft.com/en-us/library/microsoft.xrm.sdk.client.organizationservicecontext.attach.aspx

Categories