You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC与Entity Framework:向数据表中添加记录

在ASP.NET MVC中使用Entity Framework向errands表添加记录

嘿,既然你已经用EF Code First搞定了errands表,而且ApplicationDbContext里也配置好了对应的DbSet<errands> errandList,那往表里加记录其实很简单,我给你捋清楚步骤:

1. 先确认你的errands实体类没问题

首先得确保你的errands类(顺便提一句,C#规范里类名首字母建议大写,比如改成Errands,后续代码我就按你现在的类名来啦)有必要的属性,尤其是主键——EF默认会把名为Id的属性识别为主键,示例如下:

public class errands
{
    public int Id { get; set; } // EF自动识别为主键
    public string TaskTitle { get; set; } // 示例字段:任务标题
    public DateTime CreateDate { get; set; } // 示例字段:创建时间
    // 这里加你需要的其他业务字段
}

2. 在Controller里实现添加逻辑

在MVC的Controller中,你有两种常见的方式来操作数据库,我都给你列出来:

方式一:直接实例化DbContext(适合简单场景)

这种方式不需要额外配置,直接在Action里创建ApplicationDbContext实例就行:

public class ErrandsController : Controller
{
    // 显示添加表单的GET Action
    public ActionResult Create()
    {
        return View();
    }

    // 处理表单提交的POST Action
    [HttpPost]
    [ValidateAntiForgeryToken] // 防止跨站请求伪造
    public ActionResult Create(errands newErrand)
    {
        // 先验证用户输入是否符合模型规则
        if (ModelState.IsValid)
        {
            // 使用using语句自动释放DbContext资源
            using (var dbContext = new ApplicationDbContext())
            {
                // 可以给一些字段设置默认值,比如创建时间
                newErrand.CreateDate = DateTime.Now;
                // 将新实体添加到DbSet中
                dbContext.errandList.Add(newErrand);
                // 保存所有更改到数据库
                dbContext.SaveChanges();
                // 跳转回任务列表页(假设你有Index Action)
                return RedirectToAction("Index");
            }
        }
        // 如果验证失败,返回表单页面让用户重新输入
        return View(newErrand);
    }
}

方式二:依赖注入DbContext(推荐,符合MVC最佳实践)

如果你的项目配置了依赖注入(ASP.NET MVC可以用自带的DI容器,或者Autofac、Unity这类第三方容器),把ApplicationDbContext注入到Controller里会更优雅,也方便后续的单元测试:

public class ErrandsController : Controller
{
    private readonly ApplicationDbContext _dbContext;

    // 通过构造函数注入DbContext
    public ErrandsController(ApplicationDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(errands newErrand)
    {
        if (ModelState.IsValid)
        {
            newErrand.CreateDate = DateTime.Now;
            _dbContext.errandList.Add(newErrand);
            _dbContext.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(newErrand);
    }

    // 重写Dispose方法释放DbContext资源(部分DI容器会自动处理,但手动写更稳妥)
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            _dbContext.Dispose();
        }
        base.Dispose(disposing);
    }
}

3. 创建对应的Create视图

最后你需要一个表单页面让用户输入任务信息,在Views/Errands/Create.cshtml里创建如下视图:

@model errandomWeb.Models.errands

@{
    ViewBag.Title = "添加新任务";
}

<h2>添加新任务</h2>

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>任务信息</h4>
        <hr />
        <!-- 显示模型验证错误信息 -->
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        
        <!-- 任务标题输入框 -->
        <div class="form-group">
            @Html.LabelFor(model => model.TaskTitle, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.TaskTitle, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.TaskTitle, "", new { @class = "text-danger" })
            </div>
        </div>

        <!-- 这里添加你需要的其他字段的表单元素 -->

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="创建任务" class="btn btn-primary" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("返回任务列表", "Index")
</div>

<!-- 加载jQuery验证脚本,用于客户端验证 -->
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

一些小提示

  • 模型验证:记得给实体类的属性加验证特性,比如[Required]、[MaxLength(50)],这样客户端和服务端都会自动验证用户输入。
  • 编码规范:建议把errands类名改成Errands,对应的DbSet改成ErrandList,这符合C#的命名规范,代码可读性更高。
  • 事务处理:如果需要一次性添加多条记录或者执行多个数据库操作,可以用_dbContext.Database.BeginTransaction()来手动管理事务,确保操作的原子性。

内容的提问来源于stack exchange,提问作者Ken-F

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:14:17