【发布时间】:2013-01-29 19:30:06
【问题描述】:
这个错误快把我逼疯了。它曾经工作过。现在没有了。不知道是什么变化导致了它,我不能在不丢失很多东西的情况下回滚。
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; }
}
引发错误的操作
[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"
}
更新:旧工作数据库的屏幕截图
【问题讨论】:
-
如果错误出现在
db.Comments.Add(comment)中,我们真的需要知道数据库是什么......听起来你在某个地方遇到了模型不匹配。 -
@Jon 我正在使用带有代码优先迁移的实体框架(现在这只是离线本地开发)如果你是这个意思?
-
对 - 我们之前不知道它是 EF。您的
List<ranges>是如何出现在数据库中的?为什么它不像其他的那样是虚拟的ICollection<ranges>属性? -
我没有理由?它以前工作过。只是学习这一切。我将其更改为 ICollection 删除/植入数据库(无效)。
-
那么列在数据库中是什么样子的呢?您的其他多元素属性是否有效?您确实需要将 JSON 端与 EF 端分开:让它们分别工作,然后将它们放在一起。
标签: c# json data-binding asp.net-mvc-4 entity-framework-5