【问题标题】:Update Parent table from Child table in ASP.NET CORE从 ASP.NET CORE 中的子表更新父表
【发布时间】:2020-07-10 17:29:29
【问题描述】:

我有 2 张桌子; WorkSchedule(父)和 WorkShiftBid(子)。现在,当我按下WorkShiftBid 视图页面中的按钮时,我可以将WSBidStatus 更新为“已批准”。

我在两个表中都有一个状态列 (WorkScheduleStatus&WSBidStatus),我想要的是例如当按下按钮时,两个状态都将更新为“已批准”,其中两个表中的 WorkScheduleID 都是一样的。

我的控制器应该如何执行此操作?

型号:

namespace Website.Models
{
    public class WorkScheduleModel
    {
        [Key]
        public Guid WorkScheduleID { get; set; }

        public string WorkScheduleStatus { get; set; }
    }

    public class WorkShiftBidModel
    {
        [Key]
        public Guid WorkShiftBidID { get; set; }

        public string WSBidStatus { get; set; }

        public Guid WorkScheduleID { get; set; }
        [ForeignKey("WorkScheduleID")]
        public WorkScheduleModel WorkSchedules { get; set; }
    }
}

控制器:

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> WorkShiftBid(Guid? id)
        {
            SqlConnection con = new SqlConnection();
            SqlCommand com = new SqlCommand();
            SqlDataReader dr;

            connectionString();
            con.Open();
            com.Connection = con;
            com.CommandText = "update WorkShiftBid set WSBidStatus ='Approved' where WorkShiftBidID = @id ";
            com.Parameters.AddWithValue("@id", id);
            dr = com.ExecuteReader();

            var workShiftBidModel = await _context.WorkShiftBid.FindAsync(id);

            if (dr.Read())
            {
                con.Close();
                return RedirectToAction(nameof(WorkShiftBid));
            }
            else
            {
                con.Close();
                return RedirectToAction(nameof(WorkShiftBid));
            }

            void connectionString()
            {
                con.ConnectionString = ".........................";
            }
        }

查看:

@model IEnumerable<WorkShiftBidModel>

<table class="table">
    <thead>
        <tr>
            <td> 
            <th>
                .
                .
                .
            </th>
            <form method="post">
                <input type="submit" class="btn btn-success btn-block" value="Approve" asp-route-id="@item.WorkShiftBidID" asp-action="WorkShiftTab" asp-controller="Manager" />
            </form>
            </td>
        </tr>
        }
    </tbody>
</table>

【问题讨论】:

    标签: c# sql-server entity-framework asp.net-core asp.net-core-mvc


    【解决方案1】:

    我没有足够的声誉来发表评论,但是您是否同时使用实体框架和 SqlCommands?

    不过,您可以找到父键并通过 SQL 命令更新它,如下所示:

    UPDATE WorkScheduleModel SET Status = 'Approved' WHERE Id = {ID}
    

    将 {Id} 替换为您的父记录的键。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-28
      • 2020-10-31
      • 1970-01-01
      • 2021-05-03
      • 2022-01-27
      • 2013-10-03
      • 1970-01-01
      相关资源
      最近更新 更多