c# - 无法转换类型为 'System.Collections.Generic.List` 的对象 1[ModelA ]' to type ' ModelA'

标签 c# json data-binding asp.net-mvc-4 entity-framework-5

这个错误快把我逼疯了。它曾经有效。现在不是了。不确定是什么变化导致了它,我不能在不丢失很多东西的情况下回滚。

 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"
 }

更新:来自旧工作数据库的屏幕截图 enter image description here enter image description here

最佳答案

在一次替换一个文件几个小时后,我的 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/

相关文章:

javascript - Polymer 确定 dom-repeat items 上的最后一个 item

c# - 如何正确地将集合数据绑定(bind)到TabControl?

c# - 使用StackExchange.Redis和stunnel在Redis上创建SSL连接

python - 从 Scrapy json 输出中删除括号

Python - 将 JSON 键/值转换为键/值,其中值是一个数组

jquery - 如何通过从多选下拉列表中删除更改时的现有选项来附加新选项?

c# - 在 C# (winforms) 中如何同步文本框和 datagridview,以便一个中的更改显示在另一个中

c# - LINQ to Entities 无法识别方法 'Int32 Next()' 方法

c# - 如何向用户报告标准异常?

C# XML反序列化错误(2,2)