Getting conversion error on unused value when using context.SaveChages() - c#

Working on a semester-long project from a code-based that was inherited from last semester's students. Trying to add a simple method that updates a boolean field isPaid on an application class. When I call context.SaveChanges() I get the error:
SqlException: Conversion failed when converting the nvarchar value '2ab5dcc9-f6f8-464c-aa35-1832d6ed8018' to data type int.
In the code below I am passing in the ApplicationId updating the IsPaid variable. However, I'm receiving an error on the StudentId. The context.SaveChanges() method is called in other parts of the program with no such error. Could not be more confused any help would be much appreciated
Here is a picture of the debug window https://ibb.co/6WZGmMX
public void Paid(int id)
{
Application app = DbContext.Application.FirstOrDefault(a => a.ApplicationId == id);
app.IsPaid = true;
DbContext.Application.Update(app);
DbContext.SaveChanges();
}
Error message I am receiving:
An unhandled exception occurred while processing the request.
SqlException: Conversion failed when converting the nvarchar value '2ab5dcc9-f6f8-464c-aa35-1832d6ed8018' to data type int.
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, bool breakConnection, Action<Action> wrapCloseInAction)
DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)

Could you try changing your Paid method parameter to a GUID instead of integer ID?
public void Paid(Guid id)
Based on your error message, the method is passing in a Guid as an int, so that's why the error is being thrown.
If this does not work, try checking the contents of app.Id to see what that value is.
The issue is not with context.SaveChanges() itself, it is an issue with the specific data being saved in this particular method.

Related

Why is my Azure function not recording the correct exception in App Insights?

Let's say my function is the following:
public static void Run([QueueTrigger(queueName, Connection = connection)]string message,
TraceWriter logger) {
throw new CustomException();
}
Here's what the log looks like:
SomeTime [Error] ExceptionNameSpace.CustomException ---> System.Exception
When I go to App Insights and view the exception breakdown, I find this failed request under the "Exception" type. I don't even see a CustomException type listed! Why is my exception being transformed into a generic exception?
For those of you who ran into the same issue:
I found the "solution" for this by being able to recover my original exception by querying for the outerType column in the exceptions table inside the Analytics part of App Insights. Strange that the generic exception shows up under the "type" column but "outerType" is my original exception.

How to handle OdataException in DefaultODataPathHandler.Parse at global level?

DefaultODataPathHandler.Parse(string serviceRoot, string odataPath, IServiceProvider requestContainer)
is throwing ODataException when I try to send a wrong data type to a
OData controller function. For example, calling GetOrders(date = 20181001), (with an integer instead of a date (2018-10-01)), throws ODataException with message:
not able to cast Edm.Int32 to Emd.DateTime
How can I handle this exception at global level?

What causes a cast object type issue?

I am trying to create a webAPI with Visual Studio 2012. I've followed the provided Microsoft ASP.NET tutorial.
So I've got the class, repository and controller down. The software is able to to run and connect with the database. When I run and make the API call, this error occurs:
Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[ReservationsAPI.Contact]' to type 'System.Collections.Generic.IEnumerable`1[ReservationsAPI.Models.Contacts]'.
This error occurs in the method below in my repository file:
public IEnumerable<Contacts> GetAll()
{
var ContactsAll = from c in rdbc.Contacts select c;
return (IEnumerable<Contacts>)ContactsAll;
}
The error occurs at the return line. I am not sure how to deal with this error.
In your method's return type, change the type Contacts to Contact without the s. You can see this in the error message that it needs to be Contact.

Artificially create a connection timeout error in .net

I am using asp.net MVC framework and using EntityFramework to connect to database. Sometimes while connecting to database I get timeout error. These errors are very rare.
System.Data.Entity.Infrastructure.DbUpdateException:
An error occurred while updating the entries. See the inner exception for details. ---> System.Data.UpdateException: An error occurred while updating the entries.
See the inner exception for details. ---> System.Data.SqlClient.SqlException:
Timeout expired. The timeout period elapsed prior to
completion of the operation or the server is not responding.
var myList = new List<MyConnection>();
using (var db = new MyDb())
{
var activeConns = db.Connections
.Where(c => c.Key == tKey)
.Where(c => c.IsActive)
.ToList();
if (activeConns.Count > 0)
{
//Some custom logic
myList.add(conn);
}
return myList;
}
I am not setting any connection timeout period. Is there any best practice when working with Entity Framework?
How can I generate this kind of defect artificially so I can test our software?
The way we've handled this sort of thing in our code base is to use mock objects - allowing us to swap out the real implementation (for example, database) with a fake implementation used only for testing.
From the client's perspective, the fake one behaves the same, but we have more control over the behaviour for testing things like errors (throw a timeout error on 5th request for example).
Mocking Entity Framework Context is another SO question that goes into a bit more detail on how to set this up, specifically for EntityFramework.
You will probably need to use Reflection to throw SQL Timeout Exception.
Check this article for help :
http://blog.developers.ba/post/2009/03/08/SqlException-class-doesnt-have-public-constructor.aspx

Problem with c# webservice, referencing a method and a type

I have run into a bit of a problem, well not sure if it is a problem, but would like some advice.
I have developed a c# webservice in vs2010 and when I debug the service i get this error in my browser
The XML element 'VoucherResponse' from namespace 'http://test.org/' references a method and a type. Change the method's message name using WebMethodAttribute or change the type's root element using the XmlRootAttribute.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The XML element 'VoucherResponse' from namespace 'test.org' references a method and a type. Change the method's message name using WebMethodAttribute or change the type's root element using the XmlRootAttribute.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Now looking at my code in at the actual class "VoucherResponse" i have,
public class VoucherResponse : AResponse
{
public Voucher Voucher { get; set; }
}
And the Voucher object looks like this
public class Voucher
{
public string PIN { get; set; }
public string Serial { get; set; }
public string Batch { get; set; }
}
Now in one of my web methods I return the VoucherResponse and I am assuming that this error occurs when it is reflected through and checked.
Has anyone had a similar problem with this before, or can anyone give me some advice on this?
Thanks
I found another case that raises the error! Here's my code:
[WebMethod]
public CheckUpdateResponse CheckUpdate()
{
...
}
Ok, let me explain: CheckUpdateResponse is a structure I defined in my code, CheckUpdate() is a method. So, in the WSDL .NET add automatically a Response suffix to the method name CheckUpdate.
Et voilĂ : it finds a duplicate element and gives the error "Change the method's message name using WebMethodAttribute..."
Solution? I renamed the returned type from CheckUpdateResponse to CheckUpdateResult and now everything works fine!
I hope this will help someone! I lost a lot of time on this...
Apparently, SOAP cannot handle methods that have the same name as their return type.
You can fix it by reading the error, and acting accordingly:
public class VoucherResponse
{
[WebMethod(MessageName="TheVoucher")]
public Voucher Voucher{get; set;}
}
I had the same issue, but in my case; the application that I developed is web service client, so I don't have control on changing the WSDL\Schema.
The problem was that I had one web service with 17 operations, all of them are returning the same complex type, I got the mentioned error due to deserialization of the return type, because .Net is wrapping the return type for each output, and the serializer is throwing error:
The XML element 'XYZ' from namespace 'ABC' references a method and a type. Change the method's message name using WebMethodAttribute or change the type's root element using the XmlRootAttribute.
Solution:
I opened Reference.cs file, removed all wappered return type generated classes, and kept only one, then changed its class name to be generic, not related to the operation, it worked for me.

Categories