2015-10-06 68 views
-1

在表实体模型的最例子我看到的是这样的:Azure Table中的实体模型设计

public class CustomerEntity : TableEntity 
{ 
    public CustomerEntity(string lastName, string firstName) 
    { 
     this.PartitionKey = lastName; 
     this.RowKey = firstName; 
    } 

    public CustomerEntity() { } 

    public string Email { get; set; } 

    public string PhoneNumber { get; set; } 
} 

我们在这里看到lastname,并作为相应的分区键和行键firstname。因此,在保存和检索实体后,我可以从PartitionKeyRowKey属性中访问这些信息。但是,如果我想稍后将此模型作为json发送到客户端,那么我认为TableEntity基类的PartitionKeyRowKey不会被序列化。因此,如果我添加LastNameFirstName作为属性进行建模,则存储中将发生不必要的数据重复。最好的方式是避免存储中的数据重复,同时在模型序列化后可以访问姓氏和名字。

+0

为什么你认为'PartitionKey'和'RowKey'不会被序列化? –

+0

我记得我们使用[DataMember]属性来控制是否序列化模型属性,它似乎在web api中是不必要的... – igorGIS

+0

您可能已经考虑过这一点,但通过此设计,您只能拥有一个客户一样的名字。例如,如果您有两个名为“Chris Williams”的客户,则由于PartitionKey和RowKey的组合必须是唯一的,因此这将失败。 – ChrisW

回答

2

您可以随时使用getter方法上你的类,以避免混淆:

public class CustomerEntity : TableEntity 
{ 
    public CustomerEntity(string lastName, string firstName) 
    { 
     this.PartitionKey = lastName; 
     this.RowKey = firstName; 
    } 

    public CustomerEntity() { } 

    public string Email { get; set; } 

    public string PhoneNumber { get; set; } 

    public string FirstName { get { return this.RowKey; } } 

    public string LastName { get { return this.PartitionKey; } } 

} 

或者,您也可以将数据映射到API中的一个匿名对象并返回通过JSON:

var customerJson = new 
{ 
    Firstname = customer.RowKey, 
    LastName = customer. PartitionKey, 
    customer.Email, 
    customer.PhoneNumber 
}; 
return JsonConvert.SerializeObject(customerJson); 
+0

谢谢。但是数据会被复制吗?我的意思是存储表中FirstName和LastName的列将使用与PartitionKey和RowKey相同的值创建? – igorGIS

+0

对于应该存储在Table服务中的任何属性,该属性必须是公开的受支持类型的公有属性,这些属性公开get和set。另外,你的实体类型必须公开一个无参数的构造函数。找出最简单的方法就是试试看。查看映射选项的更新答案。 – viperguynaz