Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to cast object of type 'System.Collections.Generic.List`1[ModelA]' to type 'ModelA'

This error is driving me crazy. It used to work. Now it doesn't. Not sure what change caused it and I can't roll back without losing a lot of stuff.

 Unable to cast object of type 'System.Collections.Generic.List`1[Literrater.Models.ranges]' 
 to type 'Literrater.Models.ranges'.

Here's the model.

public class Comment
{
    [Key]
    public int CommentID { get; set; }
    public int ProjectDocID { get; set; }
    public int UserID { get; set; }
    public string text { get; set; }
    public string quote { get; set; }
    public DateTime DateCreated { get; set; }

    public virtual ICollection<CommentVote> CommentVote { get; set; }
    public virtual ICollection<CommentReply> CommentReply { get; set; }
    public virtual ICollection<CommentReport> CommentReport { get; set; }
    public ProjectDoc ProjectDoc { get; set; }
    public virtual User User { get; set; }
    public ICollection<ranges> ranges { get; set; }
}
public class ranges
{
    public int ID { get; set; }
    public string start { get; set; }
    public string end { get; set; }
    public string startOffset { get; set; }
    public string endOffset { get; set; }


}

Action that throws an error

    [HttpPost, ActionName("Create")]
    public ActionResult Create(Comment comment)
    {
        comment.DateCreated = DateTime.Now;
        comment.UserID = WebSecurity.CurrentUserId;
        db.Comments.Add(comment); //Error here
        db.SaveChanges();
        return Json(comment);

Json being posted.

 {"text":"",
  "ranges":
       [{
            "start":"/p[1]",
            "startOffset":160,
            "end":"/p[1]",
            "endOffset":234
       }],
   "quote":"es. Hadn't they ever heard of potpourri? Each incessant beep, made by the",
   "UserID":"6",
   "ProjectDocID":"1"
 }

Update: Screenshots from old working database enter image description here enter image description here

like image 797
Jed Grant Avatar asked Nov 21 '25 19:11

Jed Grant


1 Answers

After a couple of hours of replacing one file at a time it appear that my DAL Context file had this fluent API statement.

 modelBuilder.Entity<ranges>().HasRequired(p => p.Comment);

I don't know why I added it, but commenting it out made the error go away. If someone could explain it that would be sweet.

Turns out I did it so I could delete the comment, which doesn't work now.

like image 117
Jed Grant Avatar answered Nov 23 '25 09:11

Jed Grant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!