WCF Data Service is a powerful tool to expose data to third-party systems. It was based on OData protocol so we can use OData standard to generate query url such as $top, $select,$filter and so on.
Can WCF Data Service modify data in database? Yes! To implement it we should associate one data source with the data service, then we can modify the data through exposed data service.
Today I would like to share a basic knowledge about it as how to use it to do CRUD things. Before programming we should consider one important thing is that where do you want to comsume data service, in server side or client side. Data service has a good development experience in client side because of we can easily parse the JSON result using javascript mechanisim. For server side we can use VS service proxy generator to get the early bound code to consume the data service.
In this post I do investigation in server side, before start let's get a glance about the demo app.
Server
first of all we should expose tables on data service server side, in here you also can create new object to return data you wanted.
public static void InitializeService(DataServiceConfiguration config)
{
// TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
// Examples:
config.SetEntitySetAccessRule("Customers", EntitySetRights.All);
config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
}
[WebGet]//(UriTemplate = "GetCustomerByPage?pageIndex={pageIndex}")
public IQueryable<Customer> GetCustomerByPage(int pageIndex)
{
NORTHWNDEntities db=new NORTHWNDEntities();
int totalPage = (db.Customers.Count() % 10) != 0 ? db.Customers.Count() / 10 + 1 : db.Customers.Count();
if (pageIndex < totalPage)
{
return db.Customers.OrderBy(i => i.CustomerID).Skip(pageIndex * 10).Take(10);
}
else
{
return null;
}
}
Client
firs let's take a look at the Read operation, we can use LINQ grammar to operate data server as below
private NORTHWNDEntities _DB;
public CustomerDAL_EarlyBound(Uri serverUri)
{
_DB = new NORTHWNDEntities(serverUri);
}
public IEnumerable<wcfds.Customer> GetALL()
{
return _DB.Customers.ToList();
}
public wcfds.Customer Get(string id)
{
return _DB.Customers.Where(i => i.CustomerID.Equals(id)).FirstOrDefault();
}
except for using default data service query as customers we also can create own data service query as below
var query = db.Customers.AddQueryOption("filter", "startswith(CustomerID,'A') eq true").AddQueryOption("orderby","CustomerID");//ok
var query4 = db.CreateQuery<Customer>("/Customers").AddQueryOption("select","CustomerID").AddQueryOption("filter", "startswith(CustomerID,'A') eq true").AddQueryOption("orderby", "CustomerID");//ok
if you want to use later bound mechanism to consume data service in server side, you can use below statements but you will take more time in how to parse the result to CLR object.
static void RetrieveData()
{
using (HttpClient client = new HttpClient())
{
HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Get, "http://localhost:1600/WcfDataService1.svc/Customers()");
msg.Headers.Add("Accept", "application/json;odata=minimalmetadata");
var waitHandler = client.SendAsync(msg);
while (!waitHandler.IsCompleted)
{
System.Threading.Thread.Sleep(1000);
}
Trace.WriteLine(waitHandler.Result.IsSuccessStatusCode);
}
}
For CUD operations please take a look as below
public void Add(wcfds.Customer customer)
{
_DB.AddToCustomers(customer);
_DB.SaveChanges();
}
public void Delete(wcfds.Customer customer)
{
_DB.DeleteObject(customer);
_DB.SaveChanges();
}
public void Update(wcfds.Customer customer)
{
_DB.UpdateObject(customer);
_DB.SaveChanges();
}
Resource
WCF Data Service Documents
http://msdn.microsoft.com/en-us/library/ee358708(v=vs.110).aspx
WCF Data Service Attribute Definition
http://msdn.microsoft.com/en-us/library/ee358710(v=vs.110).aspx
WCF Data Service Query Expression
http://msdn.microsoft.com/en-us/library/ee358710(v=vs.110).aspx
OData URL Conventions
http://www.odata.org/documentation/odata-version-2-0/uri-conventions/