I’ve implemented a web service and I am calling it via ajax.
Note: My entities have been made for an entity framework code first purpose.
My ajax looks as follows:
$.ajax({
type: "GET",
url: "/MyProject/MyService.svc/GetEntity",
data: "entityID=1",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: AjaxSucceeded,
error: function (msg, status, extra) {
alert(status + " - " + extra);
}
});
AjaxSucceeded is simply a function with the data variable where I am simply logging the data in the console.
My GetEntity function currently looks like this:
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public MyEntity GetEntity(int entityID)
{
AccessObject accessObject = new AccessObject("MyConnectionString");
MyEntity theEntity = accessObject.GetByID(entityID);
return theEntity;
}
I have tested this with a class created purposefully for testing and it worked as expected (for example, I created a MyEntity class within the web service that was very simple, a couple of properties and no other methods etc.).
The problems arises when I return an entity that I have made for code first Entity Framework. It doesn’t work, the web service function is called multiple times and then an error appears in the console stating “Failed to load resource” referring to my service function.
For reference, here is my entity:
[DataContract(IsReference=true)]
public class MyEntity
{
#region Properties
[Key]
[DataMember]
public int ID { get; set; }
public bool SomeBoolean { get; set; }
[StringLength(1000)]
public string Description { get; set;}
#endregion
#region Relationships
public virtual SomeOtherEntity OtherEntity { get; set; }
#endregion
}
I have only set the ID to be DataMember for testing but still no success.
Could anyone point me in the correct direction? I know the web service works because other functions work and if I set up a local (within the web service) class it will return that with no issues. So I’m of the assumption that it has something to do with the entity framework attributes? I may be wrong but that’s all I can imagine.
Thank you for your time.
Oh also, for reference, my service class has the following attributes:
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
The problem is simply Entities aren’t really built for serialization. My advice would be to create a DTO, map the relevant properties across and pass that over the wire instead e.g.