How should one carry out CRUD operations on a SQL Server database using C#?
For example, let's say there is a DB table Employees
with these columns:
EmployeeID, FirstName, PostalCode
and I wish to post a new employee with info to that database. What would be an efficient method to accomplish this?
My current HttpPost
:
namespace API.Controllers
{
public class EmployeesController : ApiController
{
[HttpPost]
public void AddEmployee (Employee employee)
{
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = @"Server=.\servername;Database=Northwind;User ID=Username;Password=password;";
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "INSERT INTO Employee (EmployeeID,FirstName,PostalCode) Values (@EmployeeID, @FirstName, @Zip)";
sqlCmd.Parameters.AddWithValue("@EmployeeID", employee.EmployeeID);
sqlCmd.Parameters.AddWithValue("@FirstName", employee.FirstName);
sqlCmd.Parameters.AddWithValue("@Zip", employee.Zip);
myConnection.Open();
int rowInserted = sqlCmd.ExecuteNonQuery();
myConnection.Close();
}
}
}
And here is the Employee
model:
namespace API.Models
{
public class Employee
{
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public int Zip { get; set; }
}
}
When I test my API with Fiddler with the following input:
{ "EmployeeID":91, "FirstName":"Vader", "Zip":94221}
I get this error:
HTTP/1.1 415 Unsupported Media Type
and nothing is inserted into the database.
Any guidance would be greatly appreciated.
WebApiConfig.cs
:
namespace API
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
The raw error message generated, as per request:
HTTP/1.1 415 Unsupported Media Type
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?YzpcdXNlcnNcYW1lc2tvXGRvY3VtZW50c1x2aXN1YWwgc3R1ZGlvIDIwMTVcUHJvamVjdHNcQVBJXEFQSVxhcGlcRW1wbG95ZWVzXEFkZEVtcGxveWVl?=
X-Powered-By: ASP.NET
Date: Fri, 22 Jul 2016 15:33:06 GMT
Content-Length: 986
{"Message":"The request contains an entity body but no Content-Type header. The inferred media type 'application/octet-stream' is not supported for this resource.",
"ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'Employee' from content with media type 'application/octet-stream'.",
"ExceptionType":"System.Net.Http.UnsupportedMediaTypeException",
"StackTrace":" at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"}
Content-Type
header?application/json
?localhost:55239
, and I access myPOST
withlocalhost:55239/api/Employees/AddEmployee
.WebApiConfig
that generates in VisualStudio. I just realized that I must have deleted theRouteConfig.cs
that VS creates. I'll try to add it back and see what happens.