这个错误快把我逼疯了。它曾经有效。现在不是了。不确定是什么变化导致了它,我不能在不丢失很多东西的情况下回滚。
Unable to cast object of type 'System.Collections.Generic.List`1[Literrater.Models.ranges]'
to type 'Literrater.Models.ranges'.
这是模型。
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
[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。
{"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"
}
更新:来自旧工作数据库的屏幕截图
最佳答案
在一次替换一个文件几个小时后,我的 DAL 上下文文件似乎有这个流畅的 API 语句。
modelBuilder.Entity<ranges>().HasRequired(p => p.Comment);
我不知道为什么要添加它,但是将其注释掉会使错误消失。如果有人能解释一下,那就太好了。
原来我这样做是为了删除评论,但现在不起作用。
关于c# - 无法转换类型为 'System.Collections.Generic.List` 的对象 1[ModelA ]' to type ' ModelA',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14590707/