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.
Related
How can I bypass a stackoverflow exception or is there a better way to do this? Any help is greatly appreciated!
public MetricItemDetail GetData(int itemId, int itemTwoId)
{
//some of my code goes here..
try
{
return new Class
{
Value = GetItemDetails(itemId, itemIdTwo)
};
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
return new Class();
}
}
public double GetItemDetails(int itemId, int itemTwoId)
{
var currentValue = GetData(itemId, itemTwoId); // The problem is here..this is where I get the stackoverflow exception
}
GetItemDetails and GetData methods are mutually called, it causes the "infinite" loop with stack allocations for each call, unfortunatelly stack size isn't infinite ;)
See more details here: https://www.dotnetperls.com/stackoverflowexception
StackOverflowException can't be bypased, it can't be catched, it must be avoided. It exists to protect .NET runtime from fatal crash.
Whats the Perfered Method to handle Errors in a SQL Stored Procedure when Using Entity Framework.
I have a chunk of code that uses a database context and EF to call a stored procedure. If everything is perfect, the stored procedure returns a list of keys to tell me which records were modified. If something goes wrong in the stored procedure, the transaction rolls back and I believe the response type is a string and causes this error:
The data reader has more than one field. Multiple fields are not valid for EDM primitive or enumeration types.
After doing so digging I noticed that the SQL developer had put "PRINT: ERROR MESSAGE HERE" statement to pass back a message, However the current call does not allow for this,
Here is how the call is currently being made:
var partIdsCreated = context.Database.SqlQuery<int>("EXEC My_SP #FilePath, #FileName", args).ToList();
The Current Code is expecting a list of Int and if a string is Returned it Errors out with the Error Message listed above, So what is the best way to handle errors coming back from a Stored Procedure in a Transaction Using Entity Framework 6?
Below I have provided two similar ways to handle messages returned by SQL Server. As noted in the comments, both involve the usage of the InfoMessage event on the connection.
To answer your question, I don't really know of a preferred way to do handle PRINT statements as errors, but I am also not really sure of another way to handle the output.
Solution 1: Catch Exception
public class DataLoader_01
{
public int LoadData()
{
_infoMessage = null;
using (var context = new ApplicationDbContext(#"Server=localhost\SQLEXPRESS;Database=StackOverflow;Trusted_Connection=True;"))
{
var sqlConnection = (SqlConnection)context.Database.Connection;
sqlConnection.InfoMessage += InfoMessage;
try
{
var t = context.Database.SqlQuery<int>("EXEC ErrorMessageHandling", new object[] {});
return t.First();
}
catch (EntityCommandExecutionException e)
{
if (string.IsNullOrEmpty(_infoMessage))
{
//do some error handling specific to your application
throw new ApplicationSpecificException(_infoMessage);
}
throw;
}
}
}
private void InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
_infoMessage = e.Message;
}
private string _infoMessage;
}
Solution 2: Check Field Count
public class DataLoader_02
{
public int LoadData()
{
_infoMessage = null;
using (var context = new ApplicationDbContext(#"Server=localhost\SQLEXPRESS;Database=StackOverflow;Trusted_Connection=True;"))
{
var sqlConnection = (SqlConnection)context.Database.Connection;
sqlConnection.InfoMessage += InfoMessage;
var cmd = context.Database.Connection.CreateCommand();
cmd.CommandText = "[dbo].[SomeProc]";
try
{
context.Database.Connection.Open();
var reader = cmd.ExecuteReader();
if (reader.FieldCount == 0)
{
throw new ApplicationSpecificException(_infoMessage);
}
var result = ((IObjectContextAdapter)context).ObjectContext.Translate<int>(reader);
return result.First();
}
finally
{
context.Database.Connection.Close();
}
}
}
private void InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
_infoMessage = e.Message;
}
private string _infoMessage;
}
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;
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.
I have a service method that very simply gets the information for all stores in the database. It maps the stores from EF using Auto Mapper, and returns a generic response of type StoreDTO (a simple POCO).
The problem is this: the method executes just fine, I step through all the way to the end. Every property in response has a value, nothing is null. The list is populated with items, the items in the list are valid, etc etc.
But the following code throws a NullReferenceException as soon as GetAllStores returns:
ListResponseDTO<StoreDTO> allStores = Services.Stores.Stores.GetAllStores();
EDIT: Here is a screenshot of the debugger, right when it is returning. You can see in the watch window that the values look kosher: http://i.imgur.com/rd853.png
Any help is greatly appreciated. Here is the code from the method:
public static ListResponseDTO<StoreDTO> GetAllStores()
{
ListResponseDTO<StoreDTO> response = new ListResponseDTO<StoreDTO>("Get Stores not successful");
try
{
response.Items = new List<StoreDTO>();
using (DomainEntities db = new DomainEntities(Global.ConnectionString))
{
foreach (var IndividualStore in db.Stores)
{
Mapper.CreateMap<Store, StoreDTO>();
var IndividualStoreDTO = Mapper.Map<Store, StoreDTO>(IndividualStore);
response.Items.Add(IndividualStoreDTO);
}
}
response.Message = "Store(s) retrieved successfully";
response.Success = true;
}
catch (Exception ex)
{
Logging.Log("Get All Stores", response.Message + " " + ex.ToString(), Logging.LogPriority.Error, "Store Operations");
}
return response;
}
Here is the generic DTO definition:
public class ListResponseDTO<DtoType> : ResponseDTO
{
public ListResponseDTO()
: base()
{
Items = new List<DtoType>();
}
public ListResponseDTO(string defaultMessage)
: base(defaultMessage)
{
Items = new List<DtoType>();
}
public List<DtoType> Items;
}
In case you were wondering, ResponseDTO has two properties:
bool Success
string Message
Here is the exception details, I'm afraid it's not too helpful:
System.NullReferenceException was unhandled by user code
Message=Object reference not set to an instance of an object.
Source=Infinity
StackTrace:
at PLM.Infinity.Default.GetDrawersForUser() in C:\Users\jlucas\Documents\Visual Studio 2010\PLM Source Control\Utilities\InfinityInterface\Infinity\Default.aspx.cs:line 96
InnerException:
Can you put a where clause so you return only stores that you are sure they have all fields, and see if the problem persists?
This some times happen because, somewhere in your data set, you have missing data and during debug you don't see it.
You could also put another try catch that boxes the Mapper call and see if something is happening there.
This are more suggestions then an answer.