外键列在更新时继续递增

时间:2017-02-28 14:32:31

标签: c# sql-server entity-framework

我有两个类,DepartmentEmployee,以及一个DbContextEmployeeDbContext和一个存储库类,它的CRUD操作为Employee,称为{ {1}}。

然后我创建了一个具有网格视图,详细信息视图和对象数据源的webform。我使用代码优先方法,因此解决方案将自动生成数据库。我的问题是,每当我编辑一条记录时,EmployeeRepository列都会继续递增。我做错了什么?

DepartmentId

HTML标记:

public class Department
{
    public int DepartmentId { get; set; }
    public string Name { get; set; }
    public string Location { get; set; }
    public List<Employee> Employees { get; set; }

    public Department()
    {
        DepartmentId = 0;
        Name = "";
        Location = "";
        Employees = new List<Employee>();
    }
}

public class Employee
{
    public int EmployeeId { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string Gender { get; set; }
    public decimal Salary { get; set; }
    public int DepartmentId { get; set; }
    public Department Department { get; set; }

    public Employee()
    {
        EmployeeId = 0;
        LastName = "";
        FirstName = "";
        MiddleName = "";
        Gender = "";
        Salary = 0;
        DepartmentId = 0;
        Department = new Department();
    }
}

public class EmployeeDbContext :DbContext
{
    public DbSet<Employee> Employees { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Employee>().MapToStoredProcedures();
        base.OnModelCreating(modelBuilder);
    }
}

public class EmployeeRepository 
{
    DemoEnt.EmployeeDbContext employeeDb = new DemoEnt.EmployeeDbContext();

    public List<Employee> SelectMany()
    {
        try
        {
            return employeeDb.Employees.ToList();
        }
        catch (Exception)
        {
            return new List<Employee>();
        }
    }

    public void Insert(Employee param)
    {
        employeeDb.Employees.Add(param);
        employeeDb.SaveChanges();
    }

    public void Update(Employee param)
    {
        Employee emp = employeeDb.Employees.FirstOrDefault(x => x.EmployeeId == param.EmployeeId);

        if (emp != null)
        {
            emp.LastName = param.LastName;
            emp.FirstName = param.FirstName;
            emp.Gender = param.Gender;
            emp.Salary = param.Salary;
            emp.DepartmentId = param.DepartmentId;
            employeeDb.SaveChanges();
        }
    }

    public void Delete(Employee param)
    {
        Employee emp = employeeDb.Employees.FirstOrDefault(x => x.EmployeeId == param.EmployeeId);
        if (emp != null)
        {
            employeeDb.Employees.Remove(emp);
            employeeDb.SaveChanges();
        }
    }
}

这是自动生成的存储过程:

<body>
    <form id="form1" runat="server">
    <div>

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            CellPadding="4" DataSourceID="ObjectDataSource1" ForeColor="#333333" 
            GridLines="None">
            <AlternatingRowStyle BackColor="White" />
            <Columns>
                <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
                <asp:BoundField DataField="EmployeeId" HeaderText="EmployeeId" InsertVisible="False"
                    SortExpression="EmployeeId" />
                <asp:BoundField DataField="LastName" HeaderText="LastName" 
                    SortExpression="LastName" />
                <asp:BoundField DataField="FirstName" HeaderText="FirstName" 
                    SortExpression="FirstName" />
                <asp:BoundField DataField="MiddleName" HeaderText="MiddleName" 
                    SortExpression="MiddleName" />
                <asp:BoundField DataField="Gender" HeaderText="Gender" 
                    SortExpression="Gender" />
                <asp:BoundField DataField="Salary" HeaderText="Salary" 
                    SortExpression="Salary" />
                <asp:BoundField DataField="DepartmentId" HeaderText="DepartmentId" 
                    SortExpression="DepartmentId" />
            </Columns>
            <EditRowStyle BackColor="#2461BF" />
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#EFF3FB" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#F5F7FB" />
            <SortedAscendingHeaderStyle BackColor="#6D95E1" />
            <SortedDescendingCellStyle BackColor="#E9EBEF" />
            <SortedDescendingHeaderStyle BackColor="#4870BE" />
        </asp:GridView>
        <br />
        <asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" 
            BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" 
            CellPadding="3" CellSpacing="2" DataSourceID="ObjectDataSource1" 
            DefaultMode="Insert" Height="50px" Width="125px">
            <EditRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
            <Fields>
                <asp:BoundField DataField="EmployeeId" HeaderText="EmployeeId" 
                    SortExpression="EmployeeId" InsertVisible="False"/>
                <asp:BoundField DataField="LastName" HeaderText="LastName" 
                    SortExpression="LastName" />
                <asp:BoundField DataField="FirstName" HeaderText="FirstName" 
                    SortExpression="FirstName" />
                <asp:BoundField DataField="MiddleName" HeaderText="MiddleName" 
                    SortExpression="MiddleName" />
                <asp:BoundField DataField="Gender" HeaderText="Gender" 
                    SortExpression="Gender" />
                <asp:BoundField DataField="Salary" HeaderText="Salary" 
                    SortExpression="Salary" />
                <asp:BoundField DataField="DepartmentId" HeaderText="DepartmentId" 
                    SortExpression="DepartmentId" />
                <asp:CommandField ShowInsertButton="True" />
            </Fields>
            <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
            <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
            <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
            <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
        </asp:DetailsView>
        <br />
        <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" 
            DataObjectTypeName="DemoEnt.Employee" DeleteMethod="Delete" 
            InsertMethod="Insert" SelectMethod="SelectMany" 
            TypeName="DemoEnt.EmployeeRepository" UpdateMethod="Update">
        </asp:ObjectDataSource>

    </div>
    </form>
</body>

enter image description here

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:2)

您的默认Employee构造函数包含:

Department = new Department();

基本上,如果不向部门员工查询,则每次执行更新时都会为员工重新创建部门。我建议你删除它。您还可以使用.Include(...)来获得部门员工:

Employee employee = employeeDb.Employees
    .Include(employee => employee.Department)
    .FirstOrDefault(employee => employee.EmployeeId == param.EmployeeId);