上一篇,我们讲到了如何利用BCS服务,直接连接到SQL Server数据库实现一些简单的应用程序集成的场景。看起来很不错,不是吗?
但是,事实上,直接连接到数据库也许有时候是不可能实现的任务,很多系统并不可能直接将数据库暴露出来的。地球人都知道,那样的风险极高。
那么,比较可行的是什么方式呢?我觉得很多系统倒是有公开一些服务,这些服务有的使用Web Service实现,有的不是。这都不要紧。总之,由这些服务去连接数据库,而我们做集成的时候,并不需要知道数据库在哪里?以及什么结构等等信息。
这一篇,我们讲解使用WCF作为服务,实现应用程序集成的简单步骤
1. 创建一个测试用的服务
为了快速开发,我们会将该服务宿主在一个Web Application中,所以首先我们需要创建这个Application
默认会有下面这样的项目结构
我们无需修改default.aspx.因为我们根本不使用它
为了读取数据库,我们可以创建一个LINQ to SQL数据模型
我们可以将Northwind数据库的连接定义在Server Explorer中,并且将Employees表拖拽到这个设计器中来
保存该模型。下面我们就来添加我们的服务了
修改这个IEmployeeService成下面这样
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace NorthwindService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IEmployeeService" in both code and config file together.
[ServiceContract]
public interface IEmployeeService
{
[OperationContract]
Employee[] GetEmployeeList();
[OperationContract]
Employee GetEmployeeItem(int id);
}
}
接下来修改EmployeeService.svc.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace NorthwindService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "EmployeeService" in code, svc and config file together.
public class EmployeeService : IEmployeeService
{
public Employee[] GetEmployeeList()
{
NorthwindDataContext context = new NorthwindDataContext();
return context.Employees.ToArray();
}
public Employee GetEmployeeItem(int id)
{
NorthwindDataContext context = new NorthwindDataContext();
return context.Employees.FirstOrDefault(e => e.EmployeeID == id);
}
}
}
这样就好了,下面我们可以测试该服务了
选中“EmployeeService.svc”这个文件,右键&