Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 4 Beta - You must write an attribute 'type'='object' after writing the attribute with local name '__type'

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.

like image 470
bdparrish Avatar asked Mar 12 '12 22:03

bdparrish


2 Answers

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();
    }
}
like image 91
bdparrish Avatar answered Oct 02 '22 15:10

bdparrish


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.

like image 38
Hero Avatar answered Oct 02 '22 14:10

Hero