This is a migrated thread and some comments may be shown as answers.

A circular reference was detected while serializing an object of type - and I did not include the 'circular reference'

2 Answers 796 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Matt
Top achievements
Rank 1
Matt asked on 29 Aug 2013, 02:14 PM
I'm at a lost. I've attempted to run my "Batch editing" grid with MVC3 and I keep receiving this error:
 "A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.aspnet_Users_8928C46E971F379B4E2E99263A0AD4EE44DD31017D7C2242241BF00A73BA81B3'."

 I've read other forums such as :

http://stackoverflow.com/questions/12845016/kendo-ui-invalidoperationexception-a-circular-reference-was-detected-while-se
http://docs.kendoui.com/getting-started/using-kendo-with/aspnet-mvc/helpers/grid/faq#how-do-i-avoid-circular-reference-exceptions?

I understand I can't reference a circular reference from my model in the controller or view, which I'm not and I keep receiving this error. 

I'm also using Linq with the model first approach, but I do use a metadata model to add attributes to the models fields. 
Here is some of my code.

CaseController.cs
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CustomerService.Models;
using System.Web.Security;
using System.Security.Principal;
using Kendo.Mvc.UI;
using Kendo.Mvc.Extensions;
 
namespace CustomerService.Controllers
{
    [Authorize]
    public class CaseController : Controller
    {
        private ERPEntities db = new ERPEntities();
 
        public ActionResult Cases_Read([DataSourceRequest]DataSourceRequest request)
        {
                IQueryable<CaseHeader> cases = db.CaseHeaders;
                DataSourceResult result = cases.ToDataSourceResult(request);
                return Json(result, JsonRequestBehavior.AllowGet);
        }
 
        public ActionResult Cases_Create([DataSourceRequest]DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<CaseHeader> cases)
        {
            // Will keep the inserted entitites here. Used to return the result later.
            var entities = new List<CaseHeader>();
            if (ModelState.IsValid)
            {
                foreach (var x in cases)
                {
                    // Create a new Product entity and set its properties from the posted ProductViewModel
                    var entity = new CaseHeader
                    {
                        CaseHeaderId = x.CaseHeaderId,
                        Creator = x.Creator,
                        CreatedDate = x.CreatedDate,
                        CaseLead = x.CaseLead,
                        CaseSubType1 = x.CaseSubType1,
                        CaseSubType2 = x.CaseSubType2,
                        CaseStatus = x.CaseStatus,
                        CaseTitle = x.CaseTitle,
                        CaseDescription = x.CaseDescription,
                        CaseContact = x.CaseContact
                    };
                    // Add the entity
                    db.CaseHeaders.Add(entity);
                    // Store the entity for later use
                    entities.Add(entity);
                }
                // Insert the entities in the database
                db.SaveChanges();
                 
            }
            // Return the inserted entities. The grid needs the generated ProductID. Also return any validation errors.
            return Json(entities.ToDataSourceResult(request, ModelState, x => new CaseHeader
            {
                CaseHeaderId = x.CaseHeaderId,
                Creator = x.Creator,
                CreatedDate = x.CreatedDate,
                CaseLead = x.CaseLead,
                CaseSubType1 = x.CaseSubType1,
                CaseSubType2 = x.CaseSubType2,
                CaseStatus = x.CaseStatus,
                CaseTitle = x.CaseTitle,
                CaseDescription = x.CaseDescription,
                CaseContact = x.CaseContact
            }));
        }
 
        public ActionResult Cases_Update([DataSourceRequest]DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<CaseHeader> cases)
        {
            // Will keep the updated entitites here. Used to return the result later.
            var entities = new List<CaseHeader>();
            if (ModelState.IsValid)
            {
                foreach (var x in cases)
                {
                    // Create a new Product entity and set its properties from the posted ProductViewModel
                    var entity = new CaseHeader
                    {
                        CaseHeaderId = x.CaseHeaderId,
                        Creator = x.Creator,
                        CreatedDate = x.CreatedDate,
                        CaseLead = x.CaseLead,
                        CaseSubType1 = x.CaseSubType1,
                        CaseSubType2 = x.CaseSubType2,
                        CaseStatus = x.CaseStatus,
                        CaseTitle = x.CaseTitle,
                        CaseDescription = x.CaseDescription,
                        CaseContact = x.CaseContact
                    };
                    // Store the entity for later use
                    entities.Add(entity);
                    // Attach the entity
                    db.CaseHeaders.Attach(entity);
                    // Change its state to Modified so Entity Framework can update the existing product instead of creating a new one
                    db.Entry(entity).State = EntityState.Modified;
                    // Or use ObjectStateManager if using a previous version of Entity Framework
                    // northwind.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
                }
                // Update the entities in the database
                db.SaveChanges();
            }
            // Return the updated entities. Also return any validation errors.
            return Json(entities.ToDataSourceResult(request, ModelState, x => new CaseHeader
            {
                CaseHeaderId = x.CaseHeaderId,
                Creator = x.Creator,
                CreatedDate = x.CreatedDate,
                CaseLead = x.CaseLead,
                CaseSubType1 = x.CaseSubType1,
                CaseSubType2 = x.CaseSubType2,
                CaseStatus = x.CaseStatus,
                CaseTitle = x.CaseTitle,
                CaseDescription = x.CaseDescription,
                CaseContact = x.CaseContact
            }));
        }
 
        public ActionResult Cases_Destroy([DataSourceRequest]DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<CaseHeader> cases)
        {
            // Will keep the destroyed entitites here. Used to return the result later.
            var entities = new List<CaseHeader>();
            if (ModelState.IsValid)
            {
                foreach (var x in cases)
                {
                    // Create a new Product entity and set its properties from the posted ProductViewModel
                    var entity = new CaseHeader
                    {
                        CaseHeaderId = x.CaseHeaderId,
                        Creator = x.Creator,
                        CreatedDate = x.CreatedDate,
                        CaseLead = x.CaseLead,
                        CaseSubType1 = x.CaseSubType1,
                        CaseSubType2 = x.CaseSubType2,
                        CaseStatus = x.CaseStatus,
                        CaseTitle = x.CaseTitle,
                        CaseDescription = x.CaseDescription,
                        CaseContact = x.CaseContact
                    };
                    // Store the entity for later use
                    entities.Add(entity);
                    // Attach the entity
                    db.CaseHeaders.Attach(entity);
                    // Delete the entity
                    db.CaseHeaders.Remove(entity);
                    // Or use DeleteObject if using a previous versoin of Entity Framework
                    // northwind.Products.DeleteObject(entity);
                }
                // Delete the entity in the database
                db.SaveChanges();
            }
            // Return the destroyed entities. Also return any validation errors.
            return Json(entities.ToDataSourceResult(request, ModelState, x => new CaseHeader
            {
                CaseHeaderId = x.CaseHeaderId,
                Creator = x.Creator,
                CreatedDate = x.CreatedDate,
                CaseLead = x.CaseLead,
                CaseSubType1 = x.CaseSubType1,
                CaseSubType2 = x.CaseSubType2,
                CaseStatus = x.CaseStatus,
                CaseTitle = x.CaseTitle,
                CaseDescription = x.CaseDescription,
                CaseContact = x.CaseContact
            }));
        }
    }
}

Index.cshtml

@model IEnumerable<CustomerService.Models.CaseHeader>
 
@{
    ViewBag.Title = "Index";
}
 
<h2>Your Cases</h2>
 
 
@(Html.Kendo().Grid<CustomerService.Models.CaseHeader>()
      .Name("grid")
      .Columns(columns =>
      {
          columns.Bound(x => x.CaseHeaderId);
          columns.Bound(x => x.Creator);
          columns.Bound(x => x.CreatedDate);
          columns.Bound(x => x.CaseLead);
          columns.Bound(x => x.CaseType);
          columns.Bound(x => x.CaseSubType1);
          columns.Bound(x => x.CaseSubType2);
          columns.Bound(x => x.CaseStatus);
          columns.Bound(x => x.CaseTitle);
          columns.Bound(x => x.CaseDescription);
          columns.Bound(x => x.CaseContact);
          columns.Command(commands =>
          {
              commands.Destroy(); // The "destroy" command removes data items
          }).Title("Commands").Width(200);
      })
      .ToolBar(toolbar =>
      {
          toolbar.Create(); // The "create" command adds new data items
          toolbar.Save(); // The "save" command saves the changed data items
      })
      .Editable(editable => editable.Mode(GridEditMode.InCell)) // Use in-cell editing mode
      .DataSource(dataSource =>
          dataSource.Ajax()
            .Batch(true) // Enable batch updates
            .Model(model =>
            {
                model.Id(x => x.CaseHeaderId); // Specify the property which is the unique identifier of the model
                model.Field(x => x.CaseHeaderId).Editable(false); // Make the CaseHeaderId property not editable
                model.Field(x => x.CreatedDate).Editable(false);
            })
            .Create(create => create.Action("Cases_Create", "Case")) // Action method invoked when the user saves a new data item
            .Read(read => read.Action("Cases_Read", "Case"))  // Action method invoked when the grid needs data
            .Update(update => update.Action("Cases_Update", "Case"))  // Action method invoked when the user saves an updated data item
            .Destroy(destroy => destroy.Action("Cases_Destroy", "Case")) // Action method invoked when the user removes a data item
      )
      .Pageable()
)

CaseHeader.cs  
using System;
using System.Collections.Generic;
 
namespace CustomerService.Models
{
    public partial class CaseHeader
    {
        public CaseHeader()
        {
            this.Notes = new HashSet<Note>();
        }
     
        public System.Guid CaseHeaderId { get; set; }
        public System.Guid UserId { get; set; }
        public string Creator { get; set; }
        public Nullable<System.DateTime> CreatedDate { get; set; }
        public string CaseLead { get; set; }
        public string CaseType { get; set; }
        public string CaseSubType1 { get; set; }
        public string CaseSubType2 { get; set; }
        public string CaseStatus { get; set; }
        public string CaseTitle { get; set; }
        public string CaseDescription { get; set; }
        public string CaseContact { get; set; }
     
        public virtual aspnet_Users aspnet_Users { get; set; }
        public virtual ICollection<Note> Notes { get; set; }
    }
     
}
Metadata for this model (I'm not really sure if this matters but I'm not sure) - ValidateModels.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
 
namespace CustomerService.Models
{
    [MetadataType(typeof(CaseHeaderMetaData))]
    public partial class CaseHeader
    {
    }
 
    public class CaseHeaderMetaData
    {
        public System.Guid CaseHeaderId { get; set; }
        public System.Guid UserId { get; set; }
        [MaxLength(50, ErrorMessage = "Too Long!")]
        public string Creator { get; set; }
        public Nullable<System.DateTime> CreatedDate { get; set; }
        public string CaseLead { get; set; }
        public string CaseType { get; set; }
        public string CaseSubType1 { get; set; }
        public string CaseSubType2 { get; set; }
        public string CaseStatus { get; set; }
        public string CaseTitle { get; set; }
        public string CaseDescription { get; set; }
        public string CaseContact { get; set; }
 
        public virtual aspnet_Users aspnet_Users { get; set; }
        public virtual ICollection<Note> Notes { get; set; }
    }
 
    [MetadataType(typeof(UserProfileMetaData))]
    public partial class UserProfile
    {
    }
 
    public class UserProfileMetaData
    {
        public System.Guid UserId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        [Display(Name = "Request Company")]
        public string Company { get; set; }
        public string CompanyNumber { get; set; }
 
        public virtual aspnet_Users aspnet_Users { get; set; }
    }
     
}
Any thoughts or ideas about how to fix this problem are greatly appreciated.
Thanks
 

2 Answers, 1 is accepted

Sort by
0
Chris
Top achievements
Rank 1
answered on 02 Dec 2013, 09:12 PM
Matt,

Virtually the same issue here.. Was wondering if you solved this?
0
Atanas Korchev
Telerik team
answered on 03 Dec 2013, 08:25 AM
Hello,

The problem is described in our documentation.

Regards,
Atanas Korchev
Telerik
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
Tags
Grid
Asked by
Matt
Top achievements
Rank 1
Answers by
Chris
Top achievements
Rank 1
Atanas Korchev
Telerik team
Share this question
or