WCF Data Service

本文介绍如何使用 WCF 数据服务进行数据读取、创建、更新和删除操作。通过示例展示了如何设置数据服务配置以公开数据集,并提供客户端代码实现数据的 CRUD 操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值