You need to enable JavaScript to run this app. ASP.NET MVC EF6 Code First 外键存储的人员自动补全选择实现
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC EF6 Code First 外键存储的人员自动补全选择实现

ASP.NET MVC + EF6 实现业务记录创建与人员自动选择

基础实体与DbContext定义

首先确保EF映射的实体与实际数据表结构一致,参考如下定义,注意多外键的映射配置避免EF生成歧义迁移:

// 员工表实体
public class Employee
{
    public int Id { get; set; }
    public string FullName { get; set; }
    public string WindowsLoginName { get; set; }
    public bool IsActive { get; set; }
}

// 业务记录表实体
public class BusinessRecord
{
    public int RecordId { get; set; }
    public int EmpAID { get; set; }
    public int EmpBID { get; set; }
    public virtual Employee EmpA { get; set; }
    public virtual Employee EmpB { get; set; }
}

// 数据上下文
public class InternalAppDbContext : DbContext
{
    public InternalAppDbContext() : base("InternalAppConnStr") { }
    public DbSet<Employee> Employees { get; set; }
    public DbSet<BusinessRecord> BusinessRecords { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // 显式配置两个外键的映射关系,关闭级联删除避免循环引用
        modelBuilder.Entity<BusinessRecord>()
            .HasRequired(e => e.EmpA)
            .WithMany()
            .HasForeignKey(e => e.EmpAID)
            .WillCascadeOnDelete(false);

        modelBuilder.Entity<BusinessRecord>()
            .HasRequired(e => e.EmpB)
            .WithMany()
            .HasForeignKey(e => e.EmpBID)
            .WillCascadeOnDelete(false);
    }
}

控制器实现逻辑

控制器包含三个核心方法:创建页加载、员工搜索自动补全接口、记录提交保存,注意EmpAID完全由后端根据当前登录的Windows账号生成,不接收前端传递的任何相关参数,避免越权篡改:

public class BusinessRecordController : Controller
{
    private InternalAppDbContext _dbContext = new InternalAppDbContext();

    // 加载创建页面
    public ActionResult Create()
    {
        // 校验当前登录账号是否关联有效在职员工
        var currentLoginName = User.Identity.Name;
        var currentEmployee = _dbContext.Employees
            .FirstOrDefault(e => e.WindowsLoginName == currentLoginName && e.IsActive);
        
        if (currentEmployee == null)
        {
            return HttpNotFound("当前Windows账号未匹配有效的在职员工信息");
        }
        return View();
    }

    // 自动补全搜索接口,仅返回在职员工的匹配结果
    public JsonResult SearchActiveEmployees(string term)
    {
        var matchedEmployees = _dbContext.Employees
            .Where(e => e.IsActive && e.FullName.Contains(term))
            .OrderBy(e => e.FullName)
            .Take(10)
            .Select(e => new {
                id = e.Id,
                label = e.FullName
            })
            .ToList();
        
        return Json(matchedEmployees, JsonRequestBehavior.AllowGet);
    }

    // 提交创建业务记录
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(int selectedEmpBId)
    {
        // 1. 强制从当前登录账号获取EmpAID,忽略前端传递的相关字段
        var currentLoginName = User.Identity.Name;
        var currentEmployee = _dbContext.Employees
            .FirstOrDefault(e => e.WindowsLoginName == currentLoginName && e.IsActive);
        
        if (currentEmployee == null)
        {
            ModelState.AddModelError("", "当前登录账号无有效员工关联,无法创建记录");
            return View();
        }

        // 2. 校验选中的目标员工为在职状态,避免非法ID提交
        var selectedEmployee = _dbContext.Employees
            .FirstOrDefault(e => e.Id == selectedEmpBId && e.IsActive);
        
        if (selectedEmployee == null)
        {
            ModelState.AddModelError("selectedEmpBId", "所选目标员工不存在或已离职");
            return View();
        }

        // 3. 按规则组装新记录并保存
        var newRecord = new BusinessRecord
        {
            EmpAID = currentEmployee.Id,
            EmpBID = selectedEmployee.Id
            // 其他业务字段按实际需求补充赋值
        };

        _dbContext.BusinessRecords.Add(newRecord);
        _dbContext.SaveChanges();

        return RedirectToAction("Index");
    }

    // 释放上下文资源
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            _dbContext.Dispose();
        }
        base.Dispose(disposing);
    }
}

视图页面实现

视图基于本地引用的jQuery UI Autocomplete组件实现自动补全效果,不依赖外部CDN资源,适配内网无公网访问的场景:

@* 创建页 Create.cshtml *@
@Html.AntiForgeryToken()
<div class="container">
    @using (Html.BeginForm())
    {
        <div class="form-group">
            <label>选择关联目标员工:</label>
            <input type="text" id="empSearchInput" class="form-control" placeholder="输入员工姓名关键词搜索" autocomplete="off" />
            @* 隐藏域存储选中的目标员工ID,提交时传递给后端 *@
            <input type="hidden" name="selectedEmpBId" id="selectedEmpBId" />
        </div>

        <button type="submit" class="btn btn-primary">创建业务记录</button>
    }
</div>

@section Scripts {
    @* 引用本地存储的脚本与样式文件 *@
    <link href="~/Content/jquery-ui.min.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-3.6.0.min.js"></script>
    <script src="~/Scripts/jquery-ui.min.js"></script>

    <script>
        $(function() {
            // 初始化自动补全组件
            $("#empSearchInput").autocomplete({
                source: "@Url.Action("SearchActiveEmployees", "BusinessRecord")",
                minLength: 1,
                select: function(event, ui) {
                    // 选中下拉项时,输入框展示员工姓名,隐藏域存储对应ID
                    $("#empSearchInput").val(ui.item.label);
                    $("#selectedEmpBId").val(ui.item.id);
                    return false;
                }
            });

            // 提交前校验是否已选中有效员工
            $("form").submit(function(e) {
                if (!$("#selectedEmpBId").val()) {
                    alert("请从下拉列表中选择有效的在职员工");
                    e.preventDefault();
                }
            });
        });
    </script>
}

落地注意事项

  • 自动补全接口可以根据实际重名情况扩展返回展示信息,比如在label字段后拼接部门、工号信息,方便用户区分同名员工,无需修改ID传递逻辑
  • 自动补全的最小触发长度minLength可根据实际员工姓名长度调整,比如设为2,避免单字输入触发过多无关结果
  • 所有离职员工会从搜索数据源和提交校验两个环节被拦截,不会被选中
  • 因为是内网域认证环境,Windows登录名的匹配逻辑不需要额外校验密码,直接复用MVC自带的Windows身份验证拿到的User.Identity.Name即可

内容的提问来源于stack exchange,提问作者Jimmy Ng

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.13 07:36:04