You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用C# DocumentObject模型创建Dynamodb表时遇键架构未定义错误求助

解决DynamoDB创建表时的"No defined key schema"错误

我之前用C#的Document Object模型创建DynamoDB表时也踩过这个一模一样的坑!明明觉得已经设置了键架构,结果还是报这个错,折腾了好一会儿才找到问题所在。下面是几个最常见的原因和对应的解决办法:

1. 实体类的键特性标记错误

如果你是用DocumentModel的CreateTableAsync方法(基于实体类自动生成表结构),一定要确保实体类上正确标记了哈希键特性:

[DynamoDBTable("UserProfiles")]
public class UserProfile
{
    // 必须标记[DynamoDBHashKey],不然DynamoDB识别不到主键
    [DynamoDBHashKey]
    public string UserId { get; set; }

    // 如果需要排序键,加上[DynamoDBRangeKey]
    [DynamoDBRangeKey]
    public DateTime CreatedAt { get; set; }

    // 其他属性...
}

要是漏了这个特性,哪怕你觉得逻辑上主键很明显,DocumentModel也不会自动帮你生成键架构。

2. 手动构建CreateTableRequest时键架构未正确赋值

如果是手动创建CreateTableRequest对象,很容易犯的错误是忘记给KeySchema赋值,或者赋值后不小心被覆盖了。一定要确保KeySchema包含至少一个KeyType.HASH的元素,并且和AttributeDefinitions中的属性名完全匹配(大小写敏感!):

var request = new CreateTableRequest
{
    TableName = "UserProfiles",
    // 这里必须明确设置键架构,不能留空或null
    KeySchema = new List<KeySchemaElement>
    {
        new KeySchemaElement { AttributeName = "UserId", KeyType = KeyType.HASH },
        new KeySchemaElement { AttributeName = "CreatedAt", KeyType = KeyType.RANGE }
    },
    AttributeDefinitions = new List<AttributeDefinition>
    {
        new AttributeDefinition { AttributeName = "UserId", AttributeType = ScalarAttributeType.S },
        new AttributeDefinition { AttributeName = "CreatedAt", AttributeType = ScalarAttributeType.N }
    },
    ProvisionedThroughput = new ProvisionedThroughput { ReadCapacityUnits = 5, WriteCapacityUnits = 5 }
};

注意:KeySchema里的AttributeName要和AttributeDefinitions里的完全一致,哪怕大小写错了都会导致DynamoDB识别不到键架构。

3. 调试确认请求发送前键架构不为空

有时候代码逻辑里可能会有不经意的重置操作,比如在赋值KeySchema之后又不小心执行了request.KeySchema = new List<KeySchemaElement>();这种代码。建议在调用CreateTableAsync之前加个断点,检查request.KeySchema的内容是否符合预期,确保它不是空列表或者null。

4. 混用DocumentModel和低阶API时的冲突

如果你同时混用了DocumentModel的实体类和手动构建的请求,一定要确保两者的键定义一致,不要出现一边标记了特性,另一边手动构建请求时又写错了属性名的情况。

按照上面的步骤排查,应该就能解决这个问题了!

内容的提问来源于stack exchange,提问作者timblistic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:19:58