0

I am having trouble with using my .NET Web API controller with entity framework. I got RESTful web service with client. I am using Microsoft ASP.Net Web API Client in my client side and Entity-Framework Web API controller on serverside.

When client-side app goes to AddContact method then client application crashes and gives me this error:

An unhandled exception of type 'System.AggregateException' occurred in mscorlib.dll.

I also debugged my server-side code. On the line of _contactRepository.SaveChanges(); it throws me an exception:

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

Client app code (using ASP.NET Web API client):

public void AddContact(Contact newContact)
{
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("http://localhost:21855/api/Contacts");

    var resp = client.PostAsJsonAsync<Contact>("", newContact).Result;
    resp.EnsureSuccessStatusCode();
}

Server-side code (ApiController):

// POST: api/Contacts
[ResponseType(typeof(Contact))]
public IHttpActionResult PostContact(Contact contact)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
    var lol = contact;
    var number = 1;
    _contactRepository.Add(contact);
    _contactRepository.SaveChanges();

    return CreatedAtRoute("DefaultApi", new { id = contact.ContactId }, contact);
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472
anduplats
  • 885
  • 2
  • 14
  • 24
  • Try breaking on that type of exception from the server side code; see what falls out in the locals window. http://stackoverflow.com/a/22491956/1186321 – denvercoder9 Mar 29 '16 at 18:56
  • Actually i see that object is sucessfully posted to the PostContact parameters. When i call _contactRepository.SaveChanges(); it throws an exception : An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll but was not handled in user code. – anduplats Mar 29 '16 at 20:00
  • 5
    Check message and inner exception to see more details of the error. – Marcin Iwanowski Mar 29 '16 at 20:07

0 Answers0