Entity Framework getting an sql connection

后端 未结 8 2178
栀梦
栀梦 2021-02-08 02:16

In the light of Closing connections explicitly in Entity Framework and http://msdn.microsoft.com/en-us/library/bb738582%28v=vs.90%29.aspx it seems that I should be using the con

8条回答
  •  自闭症患者
    2021-02-08 02:47

    I found out that the magic lies in ExecuteStoreCommand()

      new AdventureEntities().ExecuteStoreCommand(
            @"    UPDATE Users
                  SET lname = @lname 
                  WHERE Id = @id",
            new SqlParameter("lname", lname), new SqlParameter("id", id));
    

    Then there is no need for an explicit Connection, it actually made the code a lot cleaner. The one-liner above replaced all of the following code

      using (SqlConnection con = new SqlConnection("Persist Security Info=False;Integrated Security=true;Initial Catalog=Remember;server=(local)"))
      {
        con.Open();
        using (SqlCommand cmd = con.CreateCommand())
        {
          cmd.CommandText = @"
              UPDATE Users
              SET lname = @lname 
              WHERE Id = @id";
          cmd.Parameters.AddWithValue("lname", lname);
          cmd.Parameters.AddWithValue("id", id);
          cmd.ExecuteNonQuery();
        }
      }
    

提交回复
热议问题