Cosmos DB更新失败无法将Guid强制转换为字符串



尝试更新ASP.NET核心3.1中的Cosmos DB记录。但更新失败,并显示以下消息:"无法强制转换'System.Func'2[Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry,System.Guid]' to type 'System.Func'2[Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry,System.String]'类型的对象

错误发生在saveCangesAsync((上;简化后,代码看起来像:

// The service
public async Task<Todo> UpdateAsync(Todo entity)
{
var response = ctx.Todos.Update(entity);
await ctx.SaveChangesAsync(); // Error here
return response.Entity;
}
// The entity Todo
public class Todo
{
public Guid id { get; set; }
[Required(ErrorMessage = "Description is required")]
public string description { get; set; }
...
}
// The context
public class TodoDbContext : DbContext
{
public DbSet<Todo> Todos { get; set; }
public TodoDbContext(DbContextOptions<TodoDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultContainer("Todos");
}
}
// The controller
[HttpPut]
public async Task<IActionResult> Put(Todo todo)
{
try
{
if (ModelState.IsValid)
{
Todo td = await service.GetAsync(todo.id.ToString());
if (td != null)
{
td.description = todo.description;
var response = await service.UpdateAsync(td);
return Ok(response);
}
return BadRequest("Not found.");
}
else
{
return BadRequest(ModelState);
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);  // Exception here
}
}

我可以插入、读取,但不能更新,所以下面的代码运行良好(也有Guid(

public async Task<Todo> CreateAsync(Todo entity)
{
entity.id = Guid.NewGuid();
var response = await ctx.Todos.AddAsync(entity);
await ctx.SaveChangesAsync();
return response.Entity;
}

谢谢你的帮助!

不要使用"id",这会与自动生成的id冲突。使用另一个属性或使用"id"(大写I(来解决问题。

使用Guid作为id类型有什么原因吗?在你的Todo课上,你可以这样写:

public class Todo
{
[JsonProperty("id")
public string Id { get; set; }
[JsonProperty("description")
[Required(ErrorMessage = "Description is required")]
public string description { get; set; }
}

我假设您使用的是Cosmos DB SDK的v3版本。然后只需使用Guid.NewGuid((.ToString((将id设置为Guid(但设置为字符串类型(。

最新更新