Azure 函数的 Cosmos DB 输入绑定无法将 System.String 转换为 System.Guid
Cosmos DB input binding for Azure function cannot cast System.String to System.Guid
我有以下 Azure 函数
[FunctionName("AllProducts")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
[CosmosDB(
databaseName: "marketplace",
collectionName: "products",
SqlQuery = "SELECT * FROM product",
ConnectionStringSetting = "CosmosDbConnectionString")] IEnumerable<Product> products,
ILogger log)
{
...some magic here
}
在带有 Azure Functions 运行时的 .NET Core 3.1 上 运行 3.x。
Product.ID
属性 是 Guid
。当我向函数发送请求时,我得到 500
并在日志流中看到以下消息:
Executed 'AllProducts' (Failed,
Id=147b3de4-c6f1-445c-80ba-28e75a25ed31, Duration=48ms)Could not cast
or convert from System.String to System.Guid.
有没有办法在不更改模型的情况下从字符串转换为 guid?
型号class如下:
public class Product
{
public Guid Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
public bool IsAvailable { get; set; }
[ForeignKey("User")]
public string OwnerName { get; set; }
public User Owner { get; set; }
}
请确保您的 ID 属性 与自动生成的文档 ID 属性 没有冲突。
您可以将文档中的 属性 更改为 PropertyID 并相应地序列化它
public class Product
{
[JsonProperty("PropertyID")]
public Guid Id { get; set; }
}
CosmosDB 为每个文档自动生成 ID。在我的例子中,自动生成的 ID 看起来像 <Discriminator>|<Auto-generated guid>
。这使得绑定无法解析它作为 guid 收到的 ID。我将 Product.ID
属性 更改为 Product.ProductID
之后它开始工作了。
我有以下 Azure 函数
[FunctionName("AllProducts")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
[CosmosDB(
databaseName: "marketplace",
collectionName: "products",
SqlQuery = "SELECT * FROM product",
ConnectionStringSetting = "CosmosDbConnectionString")] IEnumerable<Product> products,
ILogger log)
{
...some magic here
}
在带有 Azure Functions 运行时的 .NET Core 3.1 上 运行 3.x。
Product.ID
属性 是 Guid
。当我向函数发送请求时,我得到 500
并在日志流中看到以下消息:
Executed 'AllProducts' (Failed, Id=147b3de4-c6f1-445c-80ba-28e75a25ed31, Duration=48ms)Could not cast or convert from System.String to System.Guid.
有没有办法在不更改模型的情况下从字符串转换为 guid?
型号class如下:
public class Product
{
public Guid Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
public bool IsAvailable { get; set; }
[ForeignKey("User")]
public string OwnerName { get; set; }
public User Owner { get; set; }
}
请确保您的 ID 属性 与自动生成的文档 ID 属性 没有冲突。 您可以将文档中的 属性 更改为 PropertyID 并相应地序列化它
public class Product
{
[JsonProperty("PropertyID")]
public Guid Id { get; set; }
}
CosmosDB 为每个文档自动生成 ID。在我的例子中,自动生成的 ID 看起来像 <Discriminator>|<Auto-generated guid>
。这使得绑定无法解析它作为 guid 收到的 ID。我将 Product.ID
属性 更改为 Product.ProductID
之后它开始工作了。