从数据库中获取id(ASP.NET)

时间:2017-08-08 06:21:35

标签: c# asp.net asp.net-mvc

我需要通过他的FIO获得面试官的身份

我有这个模型的表

 [Key]
    public int Interwier_id { get; set; }
    public string FIO { get; set; }
    public string Email { get; set; }
    public string Telephone { get; set; }
    [DataType(DataType.Date)]
    public int Birthday { get; set; }
    public string City { get; set; }
    public string Salary { get; set; }
    public string English { get; set; }
    public Nullable<int> Interview_Id { get; set; }
    public string Status { get; set; }
    public string Position { get; set; }
    public string Current_work { get; set; }
    public int Age { get { return DateTime.Now.Year - Birthday; } }
    public virtual Interview Interview { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Link> Links { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Comment> Comments { get; set; }
}

我从文本字段中获取名称

interwierName: $("#name").text()

这里是后端代码

 public ActionResult AddComment(string name,string commentText, string interwierName)
    {
        var Id = db.InterwierModels
            .Where(x => x.FIO == interwierName)
            .Select(x => new
            {
                ID = x.Interwier_id
            }).FirstOrDefault();

        //var idForCreating = Int32.Parse(Id.ToString());

        Comment cmnt = new Comment()
        {
            Author = name,
            Comment1 = commentText,
            Interview_Id = Id
        };
        db.Comments.Add(cmnt);
        db.SaveChanges();
        return Json(new { Result = "Success", Message = "Saved Successfully" });
    }

但我有这个错误

  

严重级代码描述项目文件行抑制状态   错误CS0029无法隐式转换类型'&lt; anonymous type:int ID&gt;' 'int?' SmartSolutions C:\ Users \ Eugene \ Source \ Repos \ SmartWeb \ SmartSolutions \ Controllers \ InterwierController.cs 52 Active

我该如何解决?

1 个答案:

答案 0 :(得分:0)

替换此

var Id = db.InterwierModels
            .Where(x => x.FIO == interwierName)
            .Select(x => new
            {
                ID = x.Interwier_id
            }).FirstOrDefault();

使用

    var Id = db.InterwierModels
                .Where(x => x.FIO == interwierName)
                .Select(x => x.Interwier_id)
                .FirstOrDefault();