从Microsoft.Azure.Cosmos.Tables迁移至Azure.Data.Tables:TableEntity继承问题
问题解答
核心结论
没错,你需要自行在实体类中添加PartitionKey、RowKey、ETag这些表存储要求的核心属性——因为Azure.Data.Tables中的TableEntity是密封类(sealed),无法被继承,没法像旧SDK那样通过继承自动获得这些属性。
关于继承的简单说明
在旧的Microsoft.Azure.Cosmos.Tables SDK中,TableEntity是非密封类,允许你通过继承复用它自带的PartitionKey、RowKey等属性,不用重复编写。继承的本质是子类“复用”父类的成员(属性、方法),同时可以扩展自己的专属成员(比如你的tName、tValue)。
但新SDK把TableEntity设为密封类,目的是限制继承,推荐使用普通POCO类(Plain Old CLR Object)定义实体:要么手动添加必要属性,要么实现ITableEntity接口(这个接口会强制你实现表存储所需的核心属性)。
示例代码
方式1:手动添加核心属性的POCO类
这是最直接的写法,完全自定义实体:
public class HistoricalValues { // 表存储必需的核心属性 public string PartitionKey { get; set; } public string RowKey { get; set; } public DateTimeOffset? Timestamp { get; set; } public string ETag { get; set; } // 你的自定义属性 public string tName { get; set; } public double tValue { get; set; } public int fTagId { get; set; } public string date { get; set; } }
方式2:实现ITableEntity接口
实现接口能确保你不会遗漏必需属性,接口会强制你实现所有表存储要求的成员:
public class HistoricalValues : ITableEntity { // 实现ITableEntity的必需属性 public string PartitionKey { get; set; } public string RowKey { get; set; } public DateTimeOffset? Timestamp { get; set; } public string ETag { get; set; } // 你的自定义属性 public string tName { get; set; } public double tValue { get; set; } public int fTagId { get; set; } public string date { get; set; } }
使用示例(添加实体到表存储)
// 初始化表客户端 var tableClient = new TableClient( connectionString: "你的Azure存储连接字符串", tableName: "HistoricalValuesTable"); // 创建实体 var entity = new HistoricalValues { PartitionKey = "Device-001", RowKey = DateTime.UtcNow.ToString("yyyyMMddHHmmss"), tName = "Temperature", tValue = 25.6, fTagId = 1001, date = DateTime.UtcNow.ToString("yyyy-MM-dd") }; // 添加实体 await tableClient.AddEntityAsync(entity);
内容的提问来源于stack exchange,提问作者Tim
相关产品推荐
相关产品推荐

