Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/259.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ASP.NET Core 2.0防止重复条目_C#_Asp.net Core_Asp.net Core Mvc_Asp.net Core 2.0 - Fatal编程技术网

C# ASP.NET Core 2.0防止重复条目

C# ASP.NET Core 2.0防止重复条目,c#,asp.net-core,asp.net-core-mvc,asp.net-core-2.0,C#,Asp.net Core,Asp.net Core Mvc,Asp.net Core 2.0,我对ASP.NET核心MVC非常陌生。我正在使用ASP.NET Core 2.0、C#、EntityFrameworkCore代码优先和SQL Server 2016。我设法让我的积垢操作在需要时工作 但是,我需要帮助防止用户在我的表单上注册多次。如果可能的话,我希望检查/防止控制器端代码中的重复条目,而不是数据库中的重复条目 我附上我的代码,我现在有,如果有人可以帮助。提前谢谢你 型号 public class Employee { public int EmployeeID { ge

我对ASP.NET核心MVC非常陌生。我正在使用ASP.NET Core 2.0、C#、EntityFrameworkCore代码优先和SQL Server 2016。我设法让我的积垢操作在需要时工作

但是,我需要帮助防止用户在我的表单上注册多次。如果可能的话,我希望检查/防止控制器端代码中的重复条目,而不是数据库中的重复条目

我附上我的代码,我现在有,如果有人可以帮助。提前谢谢你

型号

public class Employee
{
    public int EmployeeID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public int DepartmentID { get; set; }
    public Department Department { get; set; }

    public int AppointmentID { get; set; }
    public Appointment Appointment { get; set; }
}

public class Department
{
    public int DepartmentID { get; set; }
    public string Name { get; set; }

    public ICollection<Employee> Employees { get; set; }
}

public class Appointment
{
    public int AppointmentID { get; set; }
    public string TimeSlot { get; set; }

    public ICollection<Employee> Employees { get; set; }
}
public class EmployeeFormVM
{
    public int EmployeeID { get; set; }

    [Required(ErrorMessage = "Please enter your First Name")]
    [Display(Name = "First Name")]
    [StringLength(50)]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Please enter your Last Name")]
    [Display(Name = "Last Name")]
    [StringLength(50)]
    public string LastName { get; set; }

    [Required(ErrorMessage = "Please select your Department")]
    [Display(Name = "Department")]
    public int DepartmentID { get; set; }

    public IEnumerable<Department> Departments { get; set; }

    [Required(ErrorMessage = "Please select your Appointment")]
    [Display(Name = "Appointment")]
    public int AppointmentID { get; set; }

    public IEnumerable<Appointment> Appointments { get; set; }
}
公共类员工
{
public int EmployeeID{get;set;}
公共字符串名{get;set;}
公共字符串LastName{get;set;}
public int DepartmentID{get;set;}
公共部门部门{get;set;}
公共指定ID{get;set;}
公开约会{get;set;}
}
公共课系
{
public int DepartmentID{get;set;}
公共字符串名称{get;set;}
公共ICollection雇员{get;set;}
}
公开课任命
{
公共指定ID{get;set;}
公共字符串时隙{get;set;}
公共ICollection雇员{get;set;}
}
视图模型

public class Employee
{
    public int EmployeeID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public int DepartmentID { get; set; }
    public Department Department { get; set; }

    public int AppointmentID { get; set; }
    public Appointment Appointment { get; set; }
}

public class Department
{
    public int DepartmentID { get; set; }
    public string Name { get; set; }

    public ICollection<Employee> Employees { get; set; }
}

public class Appointment
{
    public int AppointmentID { get; set; }
    public string TimeSlot { get; set; }

    public ICollection<Employee> Employees { get; set; }
}
public class EmployeeFormVM
{
    public int EmployeeID { get; set; }

    [Required(ErrorMessage = "Please enter your First Name")]
    [Display(Name = "First Name")]
    [StringLength(50)]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Please enter your Last Name")]
    [Display(Name = "Last Name")]
    [StringLength(50)]
    public string LastName { get; set; }

    [Required(ErrorMessage = "Please select your Department")]
    [Display(Name = "Department")]
    public int DepartmentID { get; set; }

    public IEnumerable<Department> Departments { get; set; }

    [Required(ErrorMessage = "Please select your Appointment")]
    [Display(Name = "Appointment")]
    public int AppointmentID { get; set; }

    public IEnumerable<Appointment> Appointments { get; set; }
}
公共类EmployeeFormVM
{
public int EmployeeID{get;set;}
[必需(ErrorMessage=“请输入您的名字”)]
[显示(Name=“First Name”)]
[长度(50)]
公共字符串名{get;set;}
[必需(ErrorMessage=“请输入您的姓氏”)]
[显示(Name=“Last Name”)]
[长度(50)]
公共字符串LastName{get;set;}
[必需(ErrorMessage=“请选择您的部门”)]
[显示(Name=“Department”)]
public int DepartmentID{get;set;}
公共IEnumerable部门{get;set;}
[必需(ErrorMessage=“请选择您的约会”)]
[显示(Name=“约会”)]
公共指定ID{get;set;}
公共IEnumerable约会{get;set;}
}
DbContext

public class WinTenDbContext : DbContext
{
    public WinTenDbContext(DbContextOptions<WinTenDbContext> options) : base(options)
    {
    }

    public DbSet<Employee> Employees { get; set; }
    public DbSet<Department> Departments { get; set; }
    public DbSet<Appointment> Appointments { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Employee>()
            .HasKey(e => e.EmployeeID);

        modelBuilder.Entity<Employee>()
            .Property(e => e.FirstName)
            .HasColumnType("varchar(50)")
            .HasMaxLength(50)
            .IsRequired();


        modelBuilder.Entity<Employee>()
            .Property(e => e.LastName)
            .HasColumnType("varchar(50)")
            .HasMaxLength(50)
            .IsRequired();            

        modelBuilder.Entity<Department>()
            .HasKey(d => d.DepartmentID);

        modelBuilder.Entity<Department>()
            .Property(d => d.Name)
            .HasColumnType("varchar(50)")
            .HasMaxLength(50);

        modelBuilder.Entity<Appointment>()
            .HasKey(a => a.AppointmentID);

        modelBuilder.Entity<Appointment>()
            .Property(a => a.TimeSlot)
            .HasColumnType("varchar(50)")
            .HasMaxLength(50);
    }
}
公共类WinTenDbContext:DbContext
{
公共WinTenDbContext(DbContextOptions选项):基本(选项)
{
}
公共数据库集雇员{get;set;}
公共数据库集部门{get;set;}
公共数据库集约会{get;set;}
模型创建时受保护的覆盖无效(ModelBuilder ModelBuilder)
{
modelBuilder.Entity()
.HasKey(e=>e.EmployeeID);
modelBuilder.Entity()
.Property(e=>e.FirstName)
.HasColumnType(“varchar(50)”)
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity()
.Property(e=>e.LastName)
.HasColumnType(“varchar(50)”)
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity()
.HasKey(d=>d.DepartmentID);
modelBuilder.Entity()
.Property(d=>d.Name)
.HasColumnType(“varchar(50)”)
.HasMaxLength(50);
modelBuilder.Entity()
.HasKey(a=>a.AppointmentID);
modelBuilder.Entity()
.Property(a=>a.TimeSlot)
.HasColumnType(“varchar(50)”)
.HasMaxLength(50);
}
}
员工控制员

public class EmployeesController : Controller
{
    private readonly WinTenDbContext _context;

    public EmployeesController(WinTenDbContext context)
    {
        _context = context;
    }

    // GET: Employees
    public async Task<IActionResult> Index()
    {
        //return View(await _context.Employees.ToListAsync());

        var webAppDbContext = _context.Employees.Include(d => d.Department).Include(a => a.Appointment);
        return View(await webAppDbContext.ToListAsync());
    }

    // GET: Employees/Details/5
    public async Task<IActionResult> Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var employee = await _context.Employees
            .SingleOrDefaultAsync(m => m.EmployeeID == id);
        if (employee == null)
        {
            return NotFound();
        }

        return View(employee);
    }

    // GET: Employees/Create
    public IActionResult Create()
    {
        var departments = _context.Departments.ToList();
        var appointments = _context.Appointments.ToList();

        var viewModel = new EmployeeFormVM
        {
            Departments = departments,
            Appointments = appointments
        };

        return View(viewModel);
    }

    // POST: Employees/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(EmployeeFormVM employee)
    {
        if (ModelState.IsValid)
        {
            var emp = new Employee();
            {
                emp.FirstName = employee.FirstName;
                emp.LastName = employee.LastName;
                emp.DepartmentID = employee.DepartmentID;
                emp.AppointmentID = employee.AppointmentID;
            }
            _context.Add(emp);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        else
        {
            employee.Departments = _context.Departments.ToList();
            employee.Appointments = _context.Appointments.ToList();
            return View(employee);
        }
    }

    // GET: Employees/Edit/5
    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var employeevm = new EmployeeFormVM();
        {
            Employee employee = await _context.Employees.SingleOrDefaultAsync(m => m.EmployeeID == id);

            if (employee == null)
            {
                return NotFound();
            }

            employeevm.EmployeeID = employee.EmployeeID;
            employeevm.FirstName = employee.FirstName;
            employeevm.LastName = employee.LastName;

            // Retrieve list of Departments
            var departments = _context.Departments.ToList();
            employeevm.Departments = departments;
            // Set the selected department
            employeevm.DepartmentID = employee.DepartmentID;

            // Retrieve list of Appointments
            var appointments = _context.Appointments.ToList();
            employeevm.Appointments = appointments;
            // Set the selected department
            employeevm.AppointmentID = employee.AppointmentID;
        }   
        return View(employeevm);
    }

    // POST: Employees/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(EmployeeFormVM vmEdit)
    {
        if (ModelState.IsValid)
        {
            Employee employee = _context.Employees.SingleOrDefault(e => e.EmployeeID == vmEdit.EmployeeID);

            if (employee == null)
            {
                return NotFound();
            }

            employee.FirstName = vmEdit.FirstName;
            employee.LastName = vmEdit.LastName;
            employee.DepartmentID = vmEdit.DepartmentID;
            employee.AppointmentID = vmEdit.AppointmentID;

            try
            {
                _context.Update(employee);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!EmployeeExists(vmEdit.EmployeeID))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction(nameof(Index));
        }
        return View(vmEdit);
    }

    // GET: Employees/Delete/5
    public async Task<IActionResult> Delete(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var employee = await _context.Employees
            .SingleOrDefaultAsync(m => m.EmployeeID == id);
        if (employee == null)
        {
            return NotFound();
        }

        return View(employee);
    }

    // POST: Employees/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteConfirmed(int id)
    {
        var employee = await _context.Employees.SingleOrDefaultAsync(m => m.EmployeeID == id);
        _context.Employees.Remove(employee);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    private bool EmployeeExists(int id)
    {
        return _context.Employees.Any(e => e.EmployeeID == id);
    }
}
公共类EmployeesController:控制器
{
私有只读WinTenDbContext\u上下文;
公共EmployeesController(WinTenDbContext上下文)
{
_上下文=上下文;
}
//获取:员工
公共异步任务索引()
{
//返回视图(wait_context.Employees.toListSync());
var webAppDbContext=_context.Employees.Include(d=>d.Department).Include(a=>a.Appointment);
返回视图(等待webAppDbContext.ToListAsync());
}
//获取:员工/详细信息/5
公共异步任务详细信息(int?id)
{
if(id==null)
{
返回NotFound();
}
var employee=await\u context.Employees
.SingleOrDefaultAsync(m=>m.EmployeeID==id);
if(employee==null)
{
返回NotFound();
}
返回视图(员工);
}
//获取:员工/创建
public IActionResult Create()
{
var departments=_context.departments.ToList();
var appoints=_context.appoints.ToList();
var viewModel=新员工表单VM
{
部门=部门,
约会=约会
};
返回视图(viewModel);
}
//职位:员工/创建
//若要防止套印攻击,请启用要绑定到的特定属性,例如
//更多详细信息请参见http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
公共异步任务创建(EmployeeFormVM员工)
{
if(ModelState.IsValid)
{
var emp=新员工();
{
emp.FirstName=employee.FirstName;
emp.LastName=employee.LastName;
emp.DepartmentID=employee.DepartmentID;
emp.AppointmentID=employee.AppointmentID;
}
_添加(emp);
wait_context.SaveChangesAsync();
返回重定向到操作(名称(索引));
}
其他的
{
employee.Departments=_context.Departments.ToList();
employee.Appointments=_context.appoints.ToList();
返回视图(员工);
}
}
//获取:雇员/编辑/5
公共异步任务编辑(int?id)
{
if(id==null)
{
返回NotFound();
}
var employeevm=new EmployeeFormVM();
{
Employee=await_context.Employees.SingleOrDefaultAsync(m=>m.EmployeeID==id);
if(employee==null)
{
返回NotFound();
}
employeevm.EmployeeID
Employee existingEmployee = await _context.Employees.SingleOrDefaultAsync(
    m => m.FirstName == employee.FirstName && m.LastName == employee.LastName);

if (existingEmployee != null)
{
    // The employee already exists.
    // Do whatever you need to do - This is just an example.
    ModelState.AddModelError(string.Empty, "This employee already exists.");
    employee.Departments = _context.Departments.ToList();
    employee.Appointments = _context.Appointments.ToList();
    return View(employee);
}

// Your existing code for creating a new employee.
@using (Html.BeginForm("Create", "Employees"))
{
    @Html.ValidationSummary(true)
    ...