C# asp.net。如何从数据库中删除数据

C# asp.net。如何从数据库中删除数据,c#,asp.net,database,C#,Asp.net,Database,首先,我想说我刚开始学习,我是法国人,所以请你简单解释一下。想象一下你在和一个3岁的孩子说话,我应该没事。请不要在没有任何解释的情况下用几十行代码让我超负荷工作 好的,我想做的是:我有一个非常简单的文章作者数据库表。该表有5列: First Name, Second name, Dob, Phone Nb, Place of Birth, UserId 将自动创建用户ID。我已经创建了一个表单,用户将在其中写入第一个名称和第二个名称(在两个分开的文本框中,我希望使用它获取表中的userId并使

首先,我想说我刚开始学习,我是法国人,所以请你简单解释一下。想象一下你在和一个3岁的孩子说话,我应该没事。请不要在没有任何解释的情况下用几十行代码让我超负荷工作

好的,我想做的是:我有一个非常简单的文章作者数据库表。该表有5列:

First Name, Second name, Dob, Phone Nb, Place of Birth, UserId
将自动创建
用户ID
。我已经创建了一个表单,用户将在其中写入第一个名称和第二个名称(在两个分开的文本框中,我希望使用它获取表中的userId并使用它删除整行)

这是我表格的代码

    model projet_clement.Models.HomeModel

<form method="post" action="~/home/SupressionAuteur">
    <h3>deleting author page</h3>
    <p>first name of the author to delete</p>
    <input type="text" name="Nom" />
    <p>second name of the author to delete</p>
    <input type="text" name="Prenom" /><br />
    <br />
    <input type="submit" value="Delete" />
</form>



<h3>For reminder, here's a table of the author already created</h3>

<table>
    <tr>
        <td>Nom</td>
        <td>Prenom</td>
        <td>Date de naissance</td>
        <td>N° de téléphone</td>
        <td>Département de naissance</td>
        <td>UserId</td>
    </tr>
    @foreach (var i in Model.UserList)
    {
        <tr>
            <td>@i.Nom</td>
            <td>@i.Prenom</td>
            <td>@i.Naissance</td>
            <td>@i.Numero</td>
            <td>@i.Departement</td>
            <td>@i.userId</td>
        </tr>
    }

</table>
当然不行了

当我运行代码时,userId变量永远不会得到好的值。所以我想我试图得到它的方式是错误的

我应该如何使用db.users.remove()方法?顺便问一下,这是我应该用的吗?有人告诉我

提前谢谢,我真的被卡住了:)

步骤
  • 获取用户-理想情况下,您希望使用userid(或主键)检索用户
  • 从数据库中删除用户
  • 在上下文中保存更改
  • 代码:

    [HttpGet]
    public ActionResult SupressionAuteur()
    {
         var allUsers = db.Users.Where(x => x.Nom != null);
    
         var model = new HomeModel(allUsers);
         return View(model);
    }
    
    [HttpPost]
    public ActionResult SupressionAuteur(Users formUser)
    {
        //for those who skipped french class, nom = first name and prenom = second name;)
        var userId = db.Users.Where(x => x.Nom == formUser.Nom && x.prenom == formuser.prenom);
        db.Users.Remove([What should i write here?]);
        return RedirectToAction("SupressionAuteur", "Home");
    }
    
    var user = db.Users.Single(x => x.Nom == formUser.Nom && x.prenom == formuser.prenom);
    db.Users.Remove(user);
    db.SaveChanges();