We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Grid + OData + ForeignKey give me a strange error

Hello all,

I have a strange problem, the grid work perfectly with my API OData controller they don't have any entity relation! 
But when i plug the grid with an API OData controller they have a entity relation i have an error 500 but the controller work perfectly :-(

The strange is with the grid i have an 500 error but with the URI in the browser i have nothing ...

Error code (sorry it's in french and i translate)=>

message: "the property ODataNavigationLink.Url on an navigation link « T_BEST_STORE » as null value. the property ODataNavigationLink.Url need to have a non null value, qui représente la ou les entités référencées par le lien de navigation."
stacktrace: " à Microsoft.Data.OData.WriterValidationUtils.ValidateNavigationLinkUrlPresent(ODataNavigationLink navigationLink)

↵ à Microsoft.Data.OData.VerboseJson.ODataVerboseJsonWriter.WriteDeferredNavigationLink(ODataNavigationLink navigationLink)
↵ à Microsoft.Data.OData.ODataWriterCore.<WriteEndImplementation>b__16()
↵ à Microsoft.Data.OData.ODataWriterCore.InterceptException(Action action)
↵ à Microsoft.Data.OData.ODataWriterCore.WriteEndImplementation()
↵ à Microsoft.Data.OData.ODataWriterCore.WriteEnd()
↵ à System.Web.Http.OData.Formatter.Serialization.ODataEntityTypeSerializer.WriteNavigationLinks(IEnumerable`1 navigationProperties, EntityInstanceContext entityInstanceContext, ODataWriter writer)
↵ à System.Web.Http.OData.Formatter.Serialization.ODataEntityTypeSerializer.WriteEntry(Object graph, ODataWriter writer, ODataSerializerContext writeContext)
↵ à System.Web.Http.OData.Formatter.Serialization.ODataEntityTypeSerializer.WriteObjectInline(Object graph, IEdmTypeReference expectedType, ODataWriter writer, ODataSerializerContext writeContext)
↵ à System.Web.Http.OData.Formatter.Serialization.ODataFeedSerializer.WriteFeed(IEnumerable enumerable, IEdmTypeReference feedType, ODataWriter writer, ODataSerializerContext writeContext)
↵ à System.Web.Http.OData.Formatter.Serialization.ODataFeedSerializer.WriteObjectInline(Object graph, IEdmTypeReference expectedType, ODataWriter writer, ODataSerializerContext writeContext)
↵ à System.Web.Http.OData.Formatter.Serialization.ODataFeedSerializer.WriteObject(Object graph, Type type, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
↵ à System.Web.Http.OData.Formatter.ODataMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content, HttpContentHeaders contentHeaders)
↵ à System.Web.Http.OData.Formatter.ODataMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)
↵--- Fin de la trace de la pile à partir de l'emplacement précédent au niveau duquel l'exception a été levée ---
↵ à System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
↵ à System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
↵ à System.Runtime.CompilerServices.TaskAwaiter.GetResult()
↵ à System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()"
type: "Microsoft.Data.OData.ODataException"
message: "Échec de la sérialisation du corps de la réponse par le type « ObjectContent`1 » pour le type de contenu « application/json; charset=utf-8 »."
stacktrace: ""
type: "System.InvalidOperationException"

my grid code =>


@(Html.EJ().Grid<T_PRODUCT>("RemoteBinding")
    .Datasource(ds => ds.URL(url).UpdateURL(url).InsertURL(url).RemoveURL(url))
    .EditSettings(edit =>
    {
        edit.AllowAdding()
        .AllowDeleting()
        .AllowEditing()
        .EditMode(EditMode.ExternalFormTemplate).ExternalFormTemplateID("#templateEditing");
    })
    .EnableAltRow()
    .AllowPaging()
    .AllowResizing()
    .AllowSorting()
    .AllowMultiSorting()
    .AllowGrouping()
    .AllowFiltering()
    .FilterSettings(filter =>
    {
        filter.FilterType(FilterType.Menu);
    })
    .ClientSideEvents(eve => { eve.ActionComplete("actionComplete"); })
    .ToolbarSettings(toolbar =>
    {
        toolbar.ShowToolbar().ToolbarItems(items =>
        {
            items.AddTool(ToolBarItems.Add);
            items.AddTool(ToolBarItems.Edit);
            items.AddTool(ToolBarItems.Delete);
            items.AddTool(ToolBarItems.Update);
            items.AddTool(ToolBarItems.Cancel);
            items.AddTool(ToolBarItems.PrintGrid);
            items.AddTool(ToolBarItems.ExcelExport);
            items.AddTool(ToolBarItems.WordExport);
            items.AddTool(ToolBarItems.PdfExport);
        });
    })
    .Columns(col =>
    {
        col.Field("id").HeaderText("ID").IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(20).Add();
        col.Field("title").HeaderText("Title").EditType(EditingType.String).Width(190).Add();
        col.Field("image").HeaderText("Image").EditType(EditingType.String).Width(190).Add();
        col.Field("enable").HeaderText("Is enable").EditType(EditingType.Boolean).Width(30).Add();
        col.Field("place_order").HeaderText("Order").EditType(EditingType.Numeric).Width(20).Add();
        col.Field("point").HeaderText("point").EditType(EditingType.Numeric).Width(20).Add();
    })
)

Some image : 

Doesn't work with grid



but work with browser ???



and if i use javascript grid, i have the same problem except for when i use some query :-(


//THIS WORK 
var dataManager2 = ej.DataManager("/api-v1.0/Product/");
var queryCustomer2 = ej.Query().select("id", "title", "point", "image", "enable");
$("#test2").ejGrid({
    dataSource: dataManager2,
    query: queryCustomer2,
    columns: ["id", "title", "point", "image", "enable"]
});

//BUT THIS DOESN'T WORK ...
var dataManager3 = ej.DataManager("/api-v1.0/Product/");
var queryCustomer2 = ej.Query().select("id", "title", "point", "image", "enable");
$("#test3").ejGrid({
    dataSource: dataManager3,
    columns: ["id", "title", "point", "image", "enable"]
});


Thank's for all reply :-)


5 Replies

GV Gowthami V Syncfusion Team October 29, 2015 04:48 PM UTC

Hi Philippe,

Thanks for using Syncfusion products.

Query 1: plug the grid with an API OData controller they have a entity relation i have an error 500 but the controller work perfectly

We have analyzed you issue and we are not able to reproduce the issue.

We have attached the sample below for your reference,

https://www.syncfusion.com/downloads/support/directtrac/general/ze/WebAPI_CSharp-1166410526.zip

Please provide more information about the issue like sample demo with the issue and the provided information will help to analyze the issue and provide you the response as early as possible.

Query 2:  if i use javascript grid, i have the same problem except for when i use some query

While selecting the data then we should pass the query for the grid. If we are not pass the query then it will not work.

var dataManager2 = ej.DataManager("/api-v1.0/Product/");

        var queryCustomer2 = ej.Query().select("id", "title", "point", "image", "enable");

        $("#test2").ejGrid({

            dataSource: dataManager2,

            query: queryCustomer2,

            columns: ["id", "title", "point", "image", "enable"]
        });


Regards,

Gowthami V.



MP markovic philippe October 29, 2015 09:58 PM UTC

Hi thank's for the response :-)

In your sample, the data model have no relation (foreign key). 
For example i have this model :


After generating my model with entity and generate OData web API, i have more method i my OData web API,
like this for all relation that i can have: 

        // GET: odata/Product(5)/TJ_PRODUCT_SALL
        [EnableQuery]
        public IQueryable<TJ_PRODUCT_SALL> GetTJ_PRODUCT_SALL([FromODataUri] short key)
        {
            return db.T_PRODUCT.Where(m => m.id == key).SelectMany(m => m.TJ_PRODUCT_SALL);
        }

But when i want to consume their with the grid i have an 500 error but no error with my browser. After trying all solution, in my case with adding caching option it work !

.EnableCaching().CachingPageSize(10).TimeTillExpiration(10)

But the stay the same :-( and when i try to add caching in javascript grid (because i have try all solution imaginable) i have this error :
Uncaught TypeError: Cannot read property 'pageIndex' of undefined




GV Gowthami V Syncfusion Team October 30, 2015 12:34 PM UTC

Hi Philippe,

We are sorry for the inconvenience.

We have tried the sample with your schema but we are unable to reproduce the issue.

And we have noticed that in your exception it shows “T_BEST_STORE” table which is not available in your provided schema.

So please share us the sample (with the issue)that you have used in your application which will help to analyze your issue deeply and provide you the response as early as possible.

Regards,
Gowthami V.


MP markovic philippe October 30, 2015 03:30 PM UTC

Hi,

I have create a sample project with visual studio 2013, with you can reproduce my probleme !

My OData API controller are in a specific area that is called "ApiOdata", the registration of theys API is in the file "WebApiConfig.cs" and we call him with the prefix "api-v1.0".
My database sample with the same datatable in production are in the folder "App_Data" and my model generated with EF6 is in "Model" folder. You can see in the model an many to many relation between T_PRODUCT and T_SALL.
The code of ejGrid is in the views folder "Home" and "index.cshtml" file. In this code i have not write the function to init an Rich Text Editor to create or update.

so when i launch the programme, the GET request "/api-v1.0/Product/?$inlinecount=allpages&$skip=0&$top=12" give me an 500 error but when i open this request in my browser, no problem :-(
If i want to correct this error i need to edit an Query like line 39 in index.cshtml or add chaching enable.

Thank's for all :-)

and 2 print screen of the request:






GV Gowthami V Syncfusion Team November 2, 2015 10:33 AM UTC

Hi Philippe,

From the provided code, we found that the reported issue is due to circular reference. While serializing the relational data, the circular reference error will occur due to the repetition of class.

We can resolve the issue using “ViewModel” concept as follows,


public class ProductController : ODataController

    {

        private DatabaseSampleEntities db = new DatabaseSampleEntities();


        // GET: odata/Product

        [EnableQuery]

        public IQueryable<ProductsViewModel> GetProduct()

        {

            var data= db.T_PRODUCT.Select(d => new ProductsViewModel {

            id = d.id,

            enable=d.enable,

            image=d.image,

            place_order=d.place_order,

            point= d.point,

           

            title=d.title

            }).AsQueryable();


            return data;
        }

public class ProductsViewModel

        {

            public short id { get; set; }

            public string title { get; set; }

            public Nullable<byte> point { get; set; }

            public string image { get; set; }

            public bool enable { get; set; }

            public byte place_order { get; set; }
                }


As in the above code example, we can access the fields that are needed to bind to the Grid alone. 

While using above code example, register the ViewModel to the WebApiConfig.cs class as follows,


public static class WebApiConfig

    {

        public static void Register(HttpConfiguration config)
        {
. . . .
. . . .

  builder.EntitySet<SyncfusionHelp.Areas.ApiOdata.Controllers.ProductController.ProductsViewModel>("ProductsViewModel");

            config.Routes.MapODataServiceRoute("odata", "api-v1.0", builder.GetEdmModel());

        }
    }


Refer to the below links for more clarification about the ViewModel concept,


https://rachelappel.com/2014/09/02/use-viewmodels-to-manage-data-amp-organize-code-in-asp-net-mvc-applications/

https://sampathloku.blogspot.com/2012/10/how-to-use-viewmodel-with-aspnet-mvc.html

We have modified your sample with the “ViewModel” concept and the same can be downloaded from the following link,

https://www.syncfusion.com/downloads/support/directtrac/general/SYNCFU~3899028907.ZIP

Regards,

Gowthami V.


Loader.
Live Chat Icon For mobile
Up arrow icon