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
close icon

Foreign Key Column not bind and got Error.

Hello, 
   
 I have use syncfusion grid control and when i have tried to bind foriegn key control then i received following Error.

Error

System.InvalidOperationException: A circular reference was detected while serializing an object of type 'MVCApplication.Models.City'.

My Following Code is listed Below.

Please help me to solve this problem.

Model Class : City.cs

 public partial class City
    {
        public int CityId { get; set; }
        public string CityName { get; set; }
        public int StateId { get; set; }
        public bool IsActive { get; set; }
    
        public virtual State State { get; set; }
    }


Controller Class : CityController.cs

public ActionResult Index()
        {
            var DataSource = db.Cities.ToList();
            ViewBag.datasource = DataSource;

            var DataSource1 = db.States.ToList();
            ViewBag.datasource1 = DataSource1;

            return View();
            //var cities = db.Cities.Include(c => c.State);
            //return View(cities.ToList());            
        }


View : Index.cshtml

@(Html.EJ().Grid<City>("SampleGrid")
                .Datasource((IEnumerable<object>)ViewBag.datasource)
                .AllowSorting()
                .AllowPaging()

        .Columns(col =>
        {
            col.Field("CityName").HeaderText("City").TextAlign(TextAlign.Left).Width(75).Add();

            col.Field("StateId").HeaderText("State").ForeignKeyField("StateId").ForeignKeyValue("StateName")
                .DataSource((IEnumerable<object>)ViewBag.datasource1)
                .TextAlign(TextAlign.Left).Width(75).Add();            
        }))




8 Replies

MS Mani Sankar Durai Syncfusion Team June 13, 2016 10:28 AM UTC

Hi Parth Shah, 
 
Thanks for contacting Syncfusion support. 
 
1.       We suspect that the cause of the issue is due to, the child object has a reference to a parent object and may be the parent object has a reference to child object in your model. 
             In your case the City class will have a State class property. We suspect that there is an another table called as State which link with the City table from your database since you have mentioned States in the controller page to bind another dataSource. 
            When returning the model with above schema from server, the JavaScriptSerializer will try to serialize the data. During that process it tries to serialize all properties of the City type which includes “State” type as well. However when traversing the State object the JavaScriptSerializer discovers the circular reference (the city property) and gives up by throwing the aforementioned exception. 
 
2.       We suggest you to change the Database schema to avoid circular reference error. Please refer to the below link for Database design to prevent the Circular Reference. 
  1. By using the ViewModel.
  2. Setting the ProxyCreationEnabled as false.
Please refer the below link in which a similar problem had been discussed. 
For your convenience we have prepared a sample that can be downloaded from the below link, 
 
Please let us know if you have any queries. 
 
Regards, 
Manisankar Durai. 
 



RR Rija Rabe November 4, 2016 09:34 AM UTC

Hello,
I also had this error and dig with it with both ViewModel and ForeignKey.

But now, the column of the foreign key is not bound to the grid and when I open the edit form, it always remains on the first item in the list for the dropdown list of foreign table.

Here is the controller code :

public ActionResult GridFeatures()
        {            
            var employeeDataContext = new DataClasses1DataContext().Employes.ToList();
            var foncDataSource = new DataClasses1DataContext().Fonctions.ToList();
            var empDataSource = new List<EmployesListe>();
            foreach (var emp in employeeDataContext)
            {
                var newEmp = new EmployesListe()
                    {
                        Matricule = emp.Matricule,
                        Nom = emp.Nom,
                        Prenom = emp.Prenom,
                        Fonction = emp.Fonctions,
                        SalaireBase = emp.SalaireBase,
                        SoldeConge = emp.SoldeConge,
                        Telephone1 = emp.Telephone1,
                        Telephone2 = emp.Telephone2,
                        Email = emp.Email
                    };
                empDataSource.Add(newEmp);
                foncDataSource.Add(emp.Fonctions);
            }

            ViewBag.empDataSource = empDataSource;
            ViewBag.foncDataSource = foncDataSource;
            return View();
        }

AND HERE IS THE RAZOR CODE :

              col.Field("Matricule").HeaderText("Matricule").IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(75).Add();
              col.Field("Prenom").HeaderText("Prénom").Width(75).Add();
              col.Field("Nom").HeaderText("Nom").Width(90).Add();
              col.Field("Telephone1").HeaderText("Téléphone 1").Width(75).Add();
              col.Field("Telephone2").HeaderText("Téléphone 2").Width(75).Add();
              col.Field("Email").HeaderText("Email").Width(75).Add();
              col.Field("IdFonction").HeaderText("Fonction").ForeignKeyField("IdFonction").ForeignKeyValue("Nom").DataSource((IEnumerable<object>)ViewBag.foncDataSource).Add();
              col.Field("SalaireBase").HeaderText("Salaire").Format("{0:N2}").Width(75).Add();
              col.Field("SoldeConge").HeaderText("Congé").Width(75).Add();

Would you please give me a help?
Thanks


PK Prasanna Kumar Viswanathan Syncfusion Team November 7, 2016 12:20 PM UTC

Hi Parth, 

We checked in our sample by binding the ForeignKey column and editing has been working fine in ForeignKey column at our end.  

Find the code example and sample: 


@(Html.EJ().Grid<object>("ForeignKey") 
        .Datasource((IEnumerable<object>)ViewBag.empDataSource) 
        .AllowPaging() 
        .AllowGrouping() 
        .AllowFiltering() 
        .FilterSettings(filter => { filter.FilterType(FilterType.Menu); }) 
        .EditSettings(edit => { edit.AllowAdding().AllowDeleting().AllowEditing(); }) 
        .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); 
            }); 
        }) 
        .Columns(col => 
         { 
             ---------------- 
            col.Field("EmployeeID").HeaderText("Employee Name").ForeignKeyField("EmployeeID") 
               .ForeignKeyValue("FirstName").DataSource((IEnumerable<object>)ViewBag.foncDataSource) 
               .TextAlign(TextAlign.Left).Width(90).Add(); 
             ---------------------- 
        } 
        ) 
    ) 


To find out the root cause of the issue, we need the following details. 

1. Code example of a Grid. 

2. Are you using any Editmode in the Grid? For example, InlineForm, externalForm etc. 

3. Are you facing any script error in the sample? If yes, share the stackrace of an issue.  

4. Provide the stackrace of an issue. 

5. If possible, replicate the issue in the attached sample.  

Regards, 
Prasanna Kumar N.S.V 
 



RR Rija Rabe November 8, 2016 12:31 PM UTC

Hello, and thank you for your response,

HERE IS THE ENTIREGRID CODE, Yes, I'm using the dialog edit form and I don't have any kind of script issue. Please find attached the dbml file

@(Html.EJ().Grid<object>("FlatGrid")
          .Datasource((IEnumerable<aspmvc.Models.EmployesListe>)ViewBag.empDataSource)
          .AllowScrolling()
          .AllowSorting()    /*Sorting Enabled*/
          .AllowPaging()    /*Paging Enabled*/
          .SelectionType(SelectionType.Single)
                  .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.Search);
                      });
                  })
          .AllowResizing()
          .EditSettings(edit => { edit.AllowAdding().AllowDeleting().AllowEditing().EditMode(EditMode.Dialog); })
          .Columns(col =>
          {
              col.Field("Matricule").HeaderText("Matricule").IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(75).Add();
              col.Field("Prenom").HeaderText("Prénom").Width(75).Add();
              col.Field("Nom").HeaderText("Nom").Width(90).Add();
              col.Field("Telephone1").HeaderText("Téléphone 1").Width(75).Add();
              col.Field("Telephone2").HeaderText("Téléphone 2").Width(75).Add();
              col.Field("Email").HeaderText("Email").Width(75).Add();
              col.Field("IdFonction").HeaderText("Fonction").ForeignKeyField("IdFonction").ForeignKeyValue("NomFonction").DataSource((IEnumerable<object>)ViewBag.foncDataSource).Add();
              col.Field("SalaireBase").HeaderText("Salaire").Format("{0:N2}").Width(75).Add();
              col.Field("SoldeConge").HeaderText("Congé").Width(75).Add();

          }
          ))


Attachment: dbml_104ea1be.rar


RR Rija Rabe November 8, 2016 12:53 PM UTC

I just tested the example you provide and also found a cicular reference error inside 

'Sample118577.Models.Order'

N.B : I faced another error before, telling me that a lot of classes already exist, so I deleted the .edmx models provided with the solution

Regards!


PK Prasanna Kumar Viswanathan Syncfusion Team November 9, 2016 06:19 PM UTC

Hi Rija, 

            Queries 
                                                 Response 

“Circular Reference Error” 


The circular reference error will reproduced when we have same table the object can be serialized. 

To avoid the circular reference error,  use the below code example 

            var DataSource1 = new NorthwindDataContext().Territories.ToList(); 
            var DataSource2 = new NorthwindDataContext().Regions.ToList(); 
            var empDataSource = new List<Territory2>(); 
            var foncDataSource = new List<Region2>(); 
            foreach (var emp in DataSource1) 
            { 
                var newEmp = new Territory2() 
                { 
                    TerritoryID = emp.TerritoryID, 
                    TerritoryDescription = emp.TerritoryDescription, 
                    Regio = new Region2() 
                    { 
                        RegionID = emp.Region.RegionID, 
                    } 
                    
                }; 
                empDataSource.Add(newEmp); 
            } 
            ---------------------------------- 
            ViewBag.empDataSource = empDataSource; 
            ViewBag.foncDataSource = foncDataSource; 
            return View(); 

We can also use select method to get the selected data from the table and data has been binded to the grid. For the following error please refer this link 
 


the column of the foreign key is not bound to the grid and when I open the edit form” 


In last update you have mentioned the column of the foreign key is not bound to the Grid.  

Foreign key is a field in a table which uniquely identifies a row of another table. To uniquely identify the relationship between both the tables, the Foreign key simply requires that the value of that field must exist first in a different table (the parent table). 
 
.Columns(col => 
         { 
             col.Field("TerritoryID").HeaderText("Territory ID").IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(75).Add(); 
             col.Field("Regio.RegionID").HeaderText("Employee Name").ForeignKeyField("RegionID") 
               .ForeignKeyValue("RegionDescription").DataSource((IEnumerable<object>)ViewBag.foncDataSource) 
               .TextAlign(TextAlign.Left).Width(90).Add(); 
         } 
 
In this, we have bound the datasource for the foreign key column. The datasource which we bound to the foreign key requires that the value in that RegionID field must exist first in the parent table. If the field does not exist in the parent table, it will show Null value in the column. 
 
Please share the screenshot or video demo of an issue, it will help us to provide the prompt solution. 
 



Regards, 
Prasanna Kumar N.S.V 



RR Rija Rabe November 10, 2016 11:00 AM UTC

Hello,
With the indications you gave me, I was able to solve the issue of binding. So here is what I have now :

  1. A list of employees with their respective jobs (in the grid)
  2. When requesting the edit action, a form with the selected columns and the dropdown list well configured
Now I'm faced with the CRUD operation stuff. With the Viewbag variables as data source  there seems to be no way to bind the CRUD actions to the View

Thanks


JK Jayaprakash Kamaraj Syncfusion Team November 11, 2016 12:32 PM UTC

Hi Rija, 
 
To overcome this problem, we suggest you to perform CRUD operations using  RemoteSaveAdaptor of Grid. RemoteSaveAdaptor is extended from the JsonAdaptor of the DataManager and it is used for binding local data and performs all DataManager queries in client-side. It interacts with server-side for CRUD operations to pass the modified records. Please refer to the below help document, code example and sample. 
 

@(Html.EJ().Grid<object>("ForeignKey") 
                   .Datasource(ds => ds.Json((IEnumerable<object>)ViewBag.empDataSource).UpdateURL("NormalUpdate").InsertURL("NormalInsert").RemoveURL("NormalDelete").Adaptor(AdaptorType.RemoteSaveAdaptor)) 
.. 
        .Columns(col => 
         { 
             col.Field("TerritoryID").HeaderText("Territory ID").IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(75).Add(); 
             col.Field("Regio.RegionID").HeaderText("Employee Name").ForeignKeyField("RegionID") 
               .ForeignKeyValue("RegionDescription").DataSource((IEnumerable<object>)ViewBag.foncDataSource) 
               .TextAlign(TextAlign.Left).Width(90).Add(); 
         } 
        ) 
) 
 
HomeController.cs 
 
public ActionResult NormalUpdate(Territory2 value) 
        { 
            //do your operations here 
           return Json(value, JsonRequestBehavior.AllowGet); 
        } 
 
        public ActionResult NormalInsert(Territory2 value) 
        { 
                //do your operations here 
            return Json(value, JsonRequestBehavior.AllowGet); 
        } 
 
        public ActionResult NormalDelete(int key) 
        { 
                //do your operations here 
            return Json(data, JsonRequestBehavior.AllowGet); 
        } 


 
 
Regards, 
 
Jayaprakash K. 


Loader.
Live Chat Icon For mobile
Up arrow icon