-1

I am trying to inset data from an ASP.Net Web API application into a database using Entity Framework. But I get an exception of:

An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll but was not handled in user code.

the exception happens when that method fire db.SaveChanges(); Here is the code of the post method:

public HttpResponseMessage PostTransaction(Transaction transaction)
{
    if (ModelState.IsValid)
    {
        // db.Entry(transaction).State = EntityState.Added;
        db.Transactions.Add(transaction);

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
            return Request.CreateResponse(HttpStatusCode.NotFound);
        }

        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, transaction);
        response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = transaction }));

        return response;
    }
    else
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }
}

Here is the model:

public partial class Transaction
{
    public int TrnID { get; set; }
    public string TrnSubject { get; set; }
    public int TrnCategoryID { get; set; }
    public DateTime TrnDate { get; set; }
    public int TrnAccount { get; set; }
    public bool TrnType { get; set; }
    public decimal TrnAmount { get; set; }
}
MohamedAbbas
  • 1,149
  • 4
  • 15
  • 31

2 Answers2

0

Make sure the TrnDate value is set to a value. You can print out the TrnDate value first, or place a breakpoint to see what it's value is.

This exception can be caused by inserting a null value into a non-nullable datetime field.

Edwin van Vliet
  • 567
  • 2
  • 12
0

You can get this error for various reasons i.e Not passing proper value (or a null value) to the DateTime from your code or Date entered does not fit the date range for the type of the specified for the column. Check what exact values are getting passed from your entities to the database.

You can refer the following post for reference:

Stack overflow - conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value

Community
  • 1
  • 1
Netnetter
  • 41
  • 1
  • 9