1

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.

1 Answer 1

1

I assume you're using db first which is why you're not just adding IsValid to your class. You'll notice the classes generated by Entity Framework are partial classes.

public partial class Fon_Campaign
{
    // generated properties
}

These classes are overwritten by Entity Framework if you update your model from db, so what you can do is make a new folder (let's say ExtendedEntities) and create another partial class yourself with the same namespace and class name as the generated one. Now you can add your "IsValid" method there and it won't be overwritten.

public partial class Fon_Campaign
{
    public bool IsValid()
    {
        return true;
    }
}

The second one will never get overwritten.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.