[英]Cosmos DB input binding for Azure function cannot cast System.String to System.Guid
I have the following Azure Function我有以下 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
}
It is running on .NET Core 3.1 with Azure Functions runtime 3.x.它在带有 Azure Functions 运行时 3.x 的 .NET Core 3.1 上运行。 The
Product.ID
property is Guid
. Product.ID
属性是Guid
。 When I send a request to the function I get 500
and in the log stream I see the following message:当我向该函数发送请求时,我得到
500
并在日志流中看到以下消息:
Executed 'AllProducts' (Failed, Id=147b3de4-c6f1-445c-80ba-28e75a25ed31, Duration=48ms)Could not cast or convert from System.String to System.Guid.
执行“AllProducts”(失败,Id=147b3de4-c6f1-445c-80ba-28e75a25ed31,Duration=48ms)无法从 System.String 转换或转换为 System.Guid。
Is there a way to convert from string to guid without chaning my models?有没有办法在不改变我的模型的情况下从字符串转换为 guid?
The model class is as follows:模型类如下:
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; }
}
Please make sure your Id property is not conflicting with the auto generated id property of the document.请确保您的 Id 属性与文档的自动生成的 id 属性不冲突。 You can change the property to PropertyID in the document and serialize it accordingly
您可以将文档中的属性更改为 PropertyID 并相应地对其进行序列化
public class Product
{
[JsonProperty("PropertyID")]
public Guid Id { get; set; }
}
CosmosDB has auto generated ID for each document. CosmosDB 为每个文档自动生成 ID。 In my case the auto generated id looks like
<Discriminator>|<Auto-generated guid>
.在我的情况下,自动生成的 id 看起来像
<Discriminator>|<Auto-generated guid>
。 This made it unable for the binding to parse the ID it received as a guid.这使得绑定无法解析它作为 guid 收到的 ID。 I changed the
Product.ID
property to Product.ProductID
and after that it started working.我将
Product.ID
属性更改为Product.ProductID
,然后它开始工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.