I have a simple Article class like this:
public class Article
{
[Key]
public int ArticleId { get; set; }
public string Title { get; set; }
public string PageContent { get; set; }
public System.DateTime PostedDate { get; set; }
public int? ArticlePostedBy { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
and this is my ApplicationUser class which have one to many relationship with article class :
public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim>
{
public ApplicationUser()
{
this.Articles = new HashSet<Article>();
}
public virtual ICollection<Article> Articles { get; set; }
I have configured the one to many relationship using fluent api like this:
modelBuilder.Entity<Article>()
.HasOptional<ApplicationUser>(a => a.ApplicationUser)
.WithMany(a => a.Articles)
.HasForeignKey(s => s.ArticlePostedBy);
Now, this is my controller for posting the article:
[HttpPost]
public JsonResult Index(Article article)
{
article.ArticlePostedBy = User.Identity.GetUserId<int>();
article.PostedDate = DateTime.UtcNow;
db.Articles.Add(article);
db.SaveChanges();
var usr = db.Users.FirstOrDefault(x => x.Id == article.ArticlePostedBy);
var ret = new
{
Title = article.Title,
PostedBy = article.ArticlePostedBy,
PostedByName = usr.UserName,
PostedByAvatar = db.Users.Include(s => s.Files).SingleOrDefault(s => s.Id == article.ArticlePostedBy),
PostedDate = article.PostedDate,
ArticleId = article.ArticleId
};
return Json(ret, JsonRequestBehavior.AllowGet);
}
Now, the problem arises when i try to post the data. On Submit button click, data got saved in the dbase but gives this server error--- A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.ApplicationUser_04102CD9A296DF3EA26BCA4B5FDF758BC1CD8B55C5601C2EA864BBE5FE4B7F46'. Now, i have read many articles on stack overflow but did not get any simple solution. The solution was given to disable lazy loading but I can't disable lazy loading as it is my primary need. many functions in my application would get affected due to that. Somewhere it was suggested to use ScriptIgnore. Should I use that? If yes, where to apply that or there is any other better approach. I want to apply changes only for this particular class.