Here, I explain my scenario - I have 2 projects - API (storing the Web API) and APP (storing the Xamarin.Forms). I have used EDMX to create Data models from my database in the API project in API.Models folder. I want to access the API from the APP project and hence have created similar data model classes in my APP project. Things work fine when there are no Foreign Keys present in the model class. As soon as a Foreign Key is added to any of the model classes in API project, consuming the API starts giving me a "Bad Request error"
API.Models Code
namespace API.Models
{
using System;
using System.Collections.Generic;
public partial class Lead
{
public int ID { get; set; }
public string LeadName { get; set; }
public Nullable<decimal> AssignedTo { get; set; }
public virtual User User1 { get; set; } //User is another entity in API.Models
}
}
APP.Models Code
namespace APP.Models
{
using System;
using System.Collections.Generic;
public partial class Lead
{
public int ID { get; set; }
public string LeadName { get; set; }
public Nullable<decimal> AssignedTo { get; set; }
public virtual User User1 { get; set; } //User is another entity in APP.Models
}
}
API Code
namespace APIProject.API
{
public class IssueLogController : ApiController
{
CRMEntities db = new CRMEntities();
[ResponseType(typeof(Lead))]
public async Task<IHttpActionResult> PostLead(Lead lead)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Lead.Add(lead);
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (LeadExists(lead.ID))
{
return Conflict();
}
else
{
throw;
}
}
return CreatedAtRoute("DefaultApi", new { id = lead.ID }, lead);
}
}
}
Xamarin.Forms code
Lead lead = new Lead();
lead.LeadName = txtLead.Text.Trim();
var uri = Constants.URL + "Lead/PostLead/";
HttpClient client = new HttpClient(new NativeMessageHandler());
var s = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat };
var json = JsonConvert.SerializeObject(lead, s);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(uri, content);
if (response.IsSuccessStatusCode)
{
await DisplayAlert("Message", "Your Lead has been recorded.", "OK");
}
Any ideas to resolve this?