Reputation: 2764
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.
Upvotes: 6
Views: 2168
Reputation: 411
Ran into this problem also. My situation was a little different though.
I had this structure and it would not work for me.
[DataContract]
public class MJPEGCamera : Camera
{
}
[DataContract]
public class H264Camera : Camera
{
}
[DataContract]
public class Camera
{
[DataMember]
public string cameraName { get; set; }
[DataMember]
public string address { get; set; }
[DataMember]
public string format { get; set; }
[DataMember]
public string archiveDaysUrl { get; private set; }
[DataMember]
public string archiveHoursUrl { get; private set; }
}
So I just created a factory in camera to accomplish what I needed. Hope this will help somebody who finds this answer.
Upvotes: 0
Reputation: 1433
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.
Upvotes: 1
Reputation: 4993
I had a similar problem. I fixed it by using a sort of ViewModel class that only had simple types. I translated the object returned by the DbContext into my ViewModel class and passed that back to the client.
This wouldn't work in all situations, but it did in mine.
Upvotes: 0
Reputation: 2764
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();
}
}
Upvotes: 2