I am working with the WebAPI in the new MVC 4 Beta. I came across this error when trying to get an entity that has a virtual ICollection<>
property to populate. Is there a way to get around this as of right now? I understand this is in the Beta stage, so this might be fixed down the road. It was just a curiosity if there is a solution out there for this.
I got this to work by removing the virtual keyword and making sure that the objects and collections that did have a virtual keyword were provided in the Include statement within my repository.
public class Order
{
public int ID { get; set; }
public DateTime OrderDate { get; set; }
public ICollection<Product> Products { get; set; }
}
public interface IOrderRepository
{
IQueryable<Order> Orders { get; }
void SaveOrder(Order order);
void DeleteOrder(Order order);
}
public class OrderRepository
{
StoreDbContext db = new StoreDbContext();
public IQueryable<Order> Orders
{
get { return db.Orders.Include("Products"); }
}
public void SaveOrder(Order order)
{
db.Entry(order).State = order.ID == 0 ?
EntityState.Added :
EntityState.Modified;
db.SaveChanges();
}
public void DeleteOrder(Order order)
{
db.Orders.Remove(order);
db.SaveChanges();
}
}
I had the same problem, it seems to be a problem with the default WebApi serializer. I added Json.Net as a formatter in my Global.asax.cs and it worked fine for me. I just followed this example: http://blogs.msdn.com/b/henrikn/archive/2012/02/18/using-json-net-with-asp-net-web-api.aspx
This is what I've got in my Global.asax.cs
JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
serializerSettings.Converters.Add(new IsoDateTimeConverter());
GlobalConfiguration.Configuration.Formatters[0] = new JsonNetFormatter(serializerSettings);
I just added the Json.Net package using NuGet and created the JsonNetFormatter class as explained in the post above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With