Simplest example of this, I get a collection and try to output it via Web API:
// GET api/items public IEnumerable<Item> Get() { return MyContext.Items.ToList(); }
And I get the error:
Object of type
'System.Data.Objects.ObjectQuery`1[Dcip.Ams.BO.EquipmentWarranty]' cannot be converted to type
'System.Data.Entity.DbSet`1[Dcip.Ams.BO.EquipmentWarranty]'
This is a pretty common error to do with the new proxies, and I know that I can fix it by setting:
MyContext.Configuration.ProxyCreationEnabled = false;
But that defeats the purpose of a lot of what I am trying to do. Is there a better way?
I would suggest Disable Proxy Creation only in the place where you don't need or is causing you trouble. You don't have to disable it globally you can just disable the current DB context via code...
[HttpGet] [WithDbContextApi] public HttpResponseMessage Get(int take = 10, int skip = 0) { CurrentDbContext.Configuration.ProxyCreationEnabled = false; var lista = CurrentDbContext.PaymentTypes .OrderByDescending(x => x.Id) .Skip(skip) .Take(take) .ToList(); var count = CurrentDbContext.PaymentTypes.Count(); return Request.CreateResponse(HttpStatusCode.OK, new { PaymentTypes = lista, TotalCount = count }); }
Here I only disabled the ProxyCreation in this method, because for every request there is a new DBContext created and therefore I only disabled the ProxyCreation for this case . Hope it helps
if you have navigation properties and you do not want make them non virtual, you should using JSON.NET and change configuration in App_Start to using JSON not XML!
after install JSON.NET From NuGet, insert this code in WebApiConfig.cs in Register method
var json = config.Formatters.JsonFormatter; json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects; config.Formatters.Remove(config.Formatters.XmlFormatter);
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