【问题标题】:Deleting a row using LINQ query - model mapped is not a column in table - MySqlException: Unknown column使用 LINQ 查询删除行 - 模型映射不是表中的列 - MySqlException:未知列
【发布时间】:2021-05-29 11:51:57
【问题描述】:

我正在尝试使用 blogId 从表“blog”中删除一条记录,但在单击视图中的删除按钮时收到以下错误 MySqlException:“字段列表”中的未知列“b.lastName” 据我了解,它试图使用包含 lastName 属性的视图模型。此属性未映射 [NotMapped] 所以我不确定为什么删除 LINQ 查询会这样做。

博客数据库表仅包含... |博客ID |博客内容 |用户名 |发表日期 |博客标题

        [HttpGet]
        public IActionResult Delete(int Id)
        {

            var deleteBlogID = (from b in _db.blog
                                where b.blogID == Id
                                select b).FirstOrDefault();
            
            if (deleteBlogID != null)
            {

                _db.blog.Remove(deleteBlogID);

            }

 
            return RedirectToAction("Display");
        }

型号

public class BlogViewModel
    {
        [Key]
        public int blogID { get; set; }

        public string blogTitle { get; set; }
        public string blogContent { get; set; }
        public string userID { get; set; }
        public DateTime publishedDate { get; set; }

        [NotMapped]
        public string firstName { get; set; }
        public string lastName { get; set; }
        //Wrap CommentModel in this model, so we can use two models in razor view
        public IEnumerable<CommentModel> Comments { get; set; }

    }

查看

@model IEnumerable<Project.ViewModels.BlogViewModel>


section...
               <tbody id="sortable" style="cursor:pointer;">
                    @foreach (var v in Model)
                    {
                        <tr onclick="location.href = '@(Url.Action("Display", "Blog", new { @bp = v.blogID }))'">
                            <td>@v.blogID</td>
                            <td>@v.blogTitle</td>
                            <td>@v.publishedDate</td>
                            <td>@(v.firstName + " " + v.lastName)</td>
                            <td>@Html.ActionLink("Edit", "Edit", "Blog", new { @Id = v.blogID })</td>
                            <td>@Html.ActionLink("Delete", "Delete", "Blog", new { @Id = v.blogID })</td>
                            @*<td><partial name="_DisplayEmployeePartial" model="v"></td>*@

                        </tr>
                    }
                </tbody>

数据库上下文


        public DbSet<Employee> employee { get; set; }
        public DbSet<BlogViewModel> blog { get; set; }
   

【问题讨论】:

    标签: c# asp.net-mvc model-view-controller


    【解决方案1】:

    您必须修复您的 BlogViewModel。您不仅映射了 firstName 属性。您还必须将 [NotMapped] 添加到姓氏

     [NotMapped]
     public string firstName { get; set; }
     [NotMapped]
     public string lastName { get; set; }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多