更新Azure表存储中的断开连接实体
本文关键字:断开 连接 实体 Azure 存储 更新 | 更新日期: 2023-09-27 18:17:43
我正在使用Windows Azure表存储的示例应用程序。我将尝试用一些代码来解释它:
//GetStudent is a service call
StudentDetails student = this.GetStudent(studentID);
这段代码返回给我一个StudentDetails对象,PartitionKey和RowKey都是空的,因为它们都不是我的数据合同中的数据成员。
//Update the student object
student.LastName = "New Last Name";
this.UpdateStudent(student);//Another service call
我的更新服务代码如下:
context.AttachTo(StudentDataServiceContext.studentTableName, student, "*");
context.UpdateObject(student);
context.SaveChangesWithRetries(SaveChangesOptions.ReplaceOnUpdate);
当我运行这段代码时,我得到以下错误:
One of the request input is not valid
我确实找到了一个解决这个问题的方法,并更新了UpdateService代码,如下所示:
StudentDetails temp = (from c in context.StudentTable
where c.PartitionKey == "Student" && c.RowKey == student.ID
select c).FirstOrDefault();
//Copy each and every property from student object to temp object
temp.LastName = student.LastName;
context.UpdateObject(temp);
context.SaveChangesWithRetries(SaveChangesOptions.ReplaceOnUpdate);
这很好,对象在表存储中得到更新。
但是没有更好的方法来做这件事吗?为什么AttachTo功能不能在我的情况下工作?
编辑
为了使我的问题更清楚,下面是我的StudentDetails类:
[DataContract]
public class StudentDetails
{
public string PartitionKey { get; set; }
public string RowKey { get; set; }
[DataMember]
public string First Name { get; set; }
[DataMember]
public string Last Name { get; set; }
[DataMember]
public string ID { get; set; }
}
下面是我的GetStudent方法:
BasicHttpBinding myBinding = new BasicHttpBinding();
EndpointAddress myEndpoint = new EndpointAddress(RoleEnvironment.GetConfigurationSettingValue("StudentServiceURI"));
ChannelFactory<IPatientService> myChannelFactory = new ChannelFactory<IStudentService>(myBinding, myEndpoint);
IStudentService proxy = myChannelFactory.CreateChannel();
student = proxy.GetPatient(studentID);
((IClientChannel)proxy).Close();
myChannelFactory.Close();
我觉得问题是我的GetStudent的通道工厂调用缺少与服务上下文相关的东西。我只是不知道。
您说返回的Student
对象在返回时没有PartitionKey
和RowKey
集。然后尝试更新该对象。如果在调用.Update()
之前没有自己设置PartitionKey
和RowKey
,这将失败,因为底层REST API依赖于它们。
在使用开发存储中的空表测试应用程序时发生。这是因为Development Storage当前要求存储在表中的实体的模式在允许您查询它之前已经被定义过。
解决方案
解决方法很简单,我们只需要在Windows Azure表中插入一个虚拟行,然后删除,如果应用程序运行在开发结构中。在web角色的初始化过程中,如果应用程序检查它是否运行在本地开发存储中,如果是这种情况,它添加,然后删除一个虚拟记录到应用程序的Windows Azure表中(这将是第一次完成,每个实体,当针对开发存储工作时)。
该代码可以使用扩展方法添加,例如。
更多信息:
http://msdn.microsoft.com/en-us/library/ff803365.aspx