NPersistence - .NET Persistence API

Step 9 - Edit the web form code

You are here

  • Open the ‘Default.aspx.cs’ file. This file is a child node of the ‘Default.aspx’ node.
  • Add the following code to the ‘Page_Load’ function:
    if (!IsPostBack)
    {
        lblMessage.Text = "Insert Employee details";
        DisplayAllEmployees();
    }

In addition, add the following functions in the same file:

protected void btnAdd_OnClick(object sender, EventArgs e) { if (txtEmployeeID.Text.Trim().Length > 0) { Employee newEmployee = new Employee(); newEmployee.FirstName = txtFirstName.Text; newEmployee.ID = txtEmployeeID.Text; newEmployee.LastName = txtLastName.Text;

if (!IsDuplicateOfExisting(newEmployee)) { EntityManager em = PersistenceUtils.getEm(); em.GetTransaction().Begin(); try { em.Persist(newEmployee); em.GetTransaction().Commit(); Response.Redirect("Default.aspx"); } catch (Exception e1) {
                    lblMessage.Text =
                    "<span style=\"color:red\">Problem during save</span><br />Please try again later.";
                }
            }
            else
            {
                lblMessage.Text =
                    "<span style=\"color:red\">The ID you provided is already in use.</span><br />Please change the ID and try again.";
            }
        }
        else
        {
            lblMessage.Text = "<span style=\"color:red\">The ID can't be empty</span>";
        }
    }
    private bool IsDuplicateOfExisting(Employee newEmployee)
    {
        try
        {
            EntityManager em = PersistenceUtils.getEm();
            Employee duplicateEmployee = em.Find<Employee>(typeof(Employee), newEmployee.ID);
            return duplicateEmployee != null;
        }
        catch (Exception e)
        {
            return false;
        }
    }
   protected void btnCancel_OnClick(object sender, EventArgs e)
  {
        Response.Redirect("Default.aspx");
    }
    private void DisplayAllEmployees()
    {
        EntityManager em = PersistenceUtils.getEm();
        grdEmployees.DataSource = em.CreateQuery<Employee>("from Employee", typeof(Employee)).GetResultList();
        grdEmployees.DataBind();
    }

The web site is now ready! just run the web site by clicking F5.