如何在实体框架中添加一行?

问题描述 投票:0回答:1

理论似乎是向实体框架数据表添加一条空记录,将该数据源 DataBind 到 GridView 控件,然后编辑新插入记录的索引:

Private Const ID_INDEX As Int32 = 1,
    NAME_INDEX As Int32 = 2,
    PHONE_INDEX As Int32 = 3,
    FAX_INDEX As Int32 = 4,
    EMAIL_INDEX As Int32 = 5,
    ENABL_INDEX As Int32 = 6

Protected Sub AddNew_Clicked(sender As Object, e As EventArgs) Handles lbAddNew.Click
    Dim data As New Employee()
    Using db As New DataClassesDataContext()
        db.Employees.Attach(data)
        ' db.Employees.AddObject(data)
        gridView1.DataSource = db.Employees
        gridView1.DataBind()
        Dim result As IQueryable(Of Employee) = From x As Employee In db.Employees
                                                Where x.emp_id = data.emp_id
        If (result IsNot Nothing) Then
            Dim added As Employee = result.FirstOrDefault()
            For index As Int32 = 0 To gridView1.Rows.Count - 1
                Dim cells As TableCellCollection = gridView1.Rows(index).Cells
                Dim emp_id As Int32 = CInt(cells(ID_INDEX).Text)
                If (data.emp_id = emp_id) Then
                    gridView1.EditIndex = index
                End If
            Next
        End If
    End Using
End Sub

EditIndex 值设置正确,但没有空行可供我编辑。

这是 GridView 控件:

<asp:LinkButton ID="lbAddNew" runat="server" OnClientClick="AddNew_Clicked">Add New</asp:LinkButton><br />

<asp:GridView ID="gridView1" runat="server" HorizontalAlign="Left"
    AutoGenerateColumns="False"
    AllowDeleting="True"
    AllowEditing="True"
    BorderStyle="Solid"
    PageSize="30"
    OnRowCancelingEdit="gv_RowCancelEdit"
    OnRowEditing="gv_RowEditing"
    OnRowUpdating="gv_RowUpdating"
    OnRowDataBound="gv_RowDataBound" DataKeyNames="emp_id">
    <Columns>
        <asp:CommandField ShowEditButton="True" ShowDeleteButton="true" />
        <asp:BoundField DataField="emp_id" HeaderText="ID" InsertVisible="false" ReadOnly="true" SortExpression="emp_id" />
        <asp:BoundField DataField="emp_name" HeaderText="Name" SortExpression="emp_name" />
        <asp:BoundField DataField="emp_phone" HeaderText="Phone" SortExpression="emp_phone" />
        <asp:BoundField DataField="emp_fax" HeaderText="Fax" SortExpression="emp_fax" />
        <asp:BoundField DataField="emp_email" HeaderText="Email" SortExpression="emp_email" />
        <asp:BoundField DataField="enabled" HeaderText="Enabled" SortExpression="enabled" />
    </Columns>
</asp:GridView>

如何添加空行进行编辑?

vb.net entity-framework webforms
1个回答
0
投票

这有点倒退了。通常,您不会将“空”行插入数据库,然后刷新网格来对其进行编辑。相反,您处理插入行客户端(网格)并输入值,然后在从数据网格发布保存时传递数据以组成新记录:

// C# code, my VB.Net is way outta date
[HttpPost]
public IActionResult InsertEmployee(string name, string phone, ...)
{
    try
    {
         var employee = new Employee(name, phone, ...);
         using var db = new DataClassesDataContext();
  
         db.Employees.Add(employee); // Employee will be tracked as a new item.
         db.SaveChanges();
         return Ok();  // or re-direct, however suits your front end flow.
    }
    catch (Exception ex)
    {
        // handle exception and response... or
        throw;
    }
}

尝试预插入数据行的问题是,您的数据库应该有约束,例如哪些数据是必需的,哪些数据是可选的,这意味着例如如果名称不能为空,您就无法插入没有姓名的新员工。捕获信息客户端,将数据发送到服务器,并让服务器尝试在完成时创建行。

至于插入行的行为,只需创建实体,将其添加到DbSet,然后调用

SaveChanges()
。 对现有记录执行更新时,从数据库中获取实体,设置值,然后调用
SaveChanges()
。您将看到在 Web 应用程序中来回传递实体的示例,不要遵循这些示例,因为它们几乎总是会导致跟踪错误、插入错误、重复数据等问题。Web 应用程序的工作方式与WPF 可能会通过编辑过程使 DbContext 和实体跟踪保持活动状态。 MVC/WebAPI 控制器可能给人的印象是正在发生的事情,但这是一个为了方便起见的谎言。实体不会在服务器和客户端之间往返,仅传递原始值。控制器可以根据这些值具体化新的、独立的(通常是不完整的)实体。

© www.soinside.com 2019 - 2024. All rights reserved.