让WCF数据服务在Silverlight中工作真是费劲。我用的是VS2010 RC。
我一直在努力解决需要使用
clientaccesspolicy.xml
&
crossdomain.xml
web服务器根文件夹中的文件,但我无法使其工作。我将Silverlight Web应用程序和;WCF数据服务在同一个项目中解决了这个问题,但是这里的任何建议都是好的。
但是现在我可以看到我的数据来自数据库并显示在Silverlight中的数据网格中,我以为我的麻烦已经过去了-但是没有。我可以编辑数据并且内存中的实体正在改变,但是当我调用
BeginSaveChanges
(使用适当的异步
EndSaveChanges
呼叫)我没有收到错误,但数据库中没有数据更新。
以下是我的WCF数据服务代码:
public class MyDataService : DataService<MyEntities>
{
public static void InitializeService(DataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.All);
config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
}
protected override void OnStartProcessingRequest(ProcessRequestArgs args)
{
base.OnStartProcessingRequest(args);
HttpContext context = HttpContext.Current;
HttpCachePolicy c = HttpContext.Current.Response.Cache;
c.SetCacheability(HttpCacheability.ServerAndPrivate);
c.SetExpires(HttpContext.Current.Timestamp.AddSeconds(60));
c.VaryByHeaders["Accept"] = true;
c.VaryByHeaders["Accept-Charset"] = true;
c.VaryByHeaders["Accept-Encoding"] = true;
c.VaryByParams["*"] = true;
}
}
我掐了那根绳子
OnStartProcessingRequest
Scott Hanselman文章中的代码
Creating an OData API for StackOverflow including XML and JSON in 30 minutes
以下是我的Silverlight应用程序中的代码:
private MyEntities _wcfDataServicesEntities;
private CollectionViewSource _customersViewSource;
private ObservableCollection<Customer> _customers;
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
{
_wcfDataServicesEntities = new MyEntities(new Uri("http://localhost:7156/MyDataService.svc/"));
_customersViewSource = this.Resources["customersViewSource"] as CollectionViewSource;
DataServiceQuery<Customer> query = _wcfDataServicesEntities.Customer;
query.BeginExecute(result =>
{
_customers = new ObservableCollection<Customer>();
Array.ForEach(query.EndExecute(result).ToArray(), _customers.Add);
Dispatcher.BeginInvoke(() =>
{
_customersViewSource.Source = _customers;
});
}, null);
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
_wcfDataServicesEntities.BeginSaveChanges(r =>
{
var response = _wcfDataServicesEntities.EndSaveChanges(r);
string[] results = new[]
{
response.BatchStatusCode.ToString(),
response.IsBatchResponse.ToString()
};
_customers[0].FinAssistCompanyName = String.Join("|", results);
}, null);
}
返回数据的响应字符串绑定到我的网格OK并显示“-1 | False”。
我的目的是让概念验证在这里工作,然后做适当的关注点分离,把它变成一个简单的业务线应用程序。
我花了很多时间在这上面。我快疯了。有什么办法让它工作吗?