I'm a dev with a background in Ruby and Node.js but currently working on a C# API with Entity Framework & SQL Server.
I have an Entity "Fon_Campaign", but I wanted to add some methods to this entity so I added an object "Campaign" which inherits from "Fon_Campaign", and gave to this new object a method isValid() which watch values and answers if the object is right or not.
My API method
[Route("Campaigns")]
[HttpPost]
public HttpResponseMessage CreateCampaigns([FromBody]Campaign campaign)
{
if (campaign == null)
{
ErrorMessage resp = new ErrorMessage();
resp.error = "Parameters are missing";
return Request.CreateResponse(HttpStatusCode.BadRequest, resp);
}
else if (campaign.IsValid())
{
Fon_Campaign c = campaign;
db.Fon_Campaign.Add(c); // Error: An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code, c is considering like an Campaign value and not Fon_Campaign
db.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, c);
}
else
{
ErrorMessage resp = new ErrorMessage();
// Add some explanation
resp.error = "New campaign is invalid";
return Request.CreateResponse(HttpStatusCode.BadRequest, resp);
}
}
When I attempt to save the object into my DB I'm notified this object is "Campaign" and I can't put it into the DB because I must put in a Fon_Campaign, so the cast didn't work.
My Model
public class Campaign : Fon_Campaign
{
public bool IsValid()
{
return true;
}
}
Hope you can help, or give me some indication for a best way to do it.