Call Stored Procedures from Entity Framework 6 In C# (Part 2)
Hello,
In this second part of the series on how to call stored procedures from Entity Framework 6, I will demonstrate on executing them using context.Database methods. To accomplish this, you need to perform steps 1 through 3 from this article Call Stored Procedures from Entity Framework 6 in C#. If you're done, the codes for the CRUD(Create, Update and Delete) functionalities are presented below.
private static CustomerEntities ce = new CustomerEntities(); private static void InsertCustomer() { try { var result = ce.Database.ExecuteSqlCommand("EXEC dbo.InsertCustomer @CompanyName,@ContactName,@Address,@Country,@Phone", new SqlParameter("CompanyName", "TNT Bookstore"), new SqlParameter("ContactName", "Mr T."), new SqlParameter("Address", "Lincoln Village"), new SqlParameter("Country", "UK"), new SqlParameter("Phone", "42333")); if (result == 1) { Console.WriteLine("Insert Record Successful!"); } } catch (Exception e) { //do something here } } private static void UpdateCustomer() { try { var result = ce.Database.ExecuteSqlCommand("EXEC dbo.UpdateCustomer @CustomerID, @CompanyName,@ContactName,@Address,@Country,@Phone", new SqlParameter("CustomerID", 12), new SqlParameter("CompanyName", "TNT Bookstore"), new SqlParameter("ContactName", "Mr M."), new SqlParameter("Address", "New Orleans"), new SqlParameter("Country", "USA"), new SqlParameter("Phone", "43567")); if (result == 1) { Console.WriteLine("Update Record Successful!"); } } catch (Exception) { //do something here } } private static void DeleteCustomer() { try { var result = ce.Database.ExecuteSqlCommand("EXEC dbo.DeleteCustomer @CustomerID", new SqlParameter("CustomerID", 12)); if (result == 1) { Console.WriteLine("Delete Record Successful!"); } } catch (Exception) { //do something here } } private static void GetAllCustomers() { var results = ce.Database.SqlQuery<Customer>("GetAllCustomers", "").ToList(); foreach (var item in results) { Console.WriteLine("ID:{0}, Company Name:{1}, Contact:{2}, Address: {3}, Country: {4}, Phone:{5}", item.CustomerID, item.CompanyName, item.ContactName, item.Address, item.Country, item.Phone); Console.Write("\n\n"); } }
Comments
Post a Comment