【发布时间】:2019-01-08 09:16:50
【问题描述】:
给定以下类:
class Account
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id {get; set;}
...
}
class AccountModel
{
public long Id {get; set;}
...
}
如果我调用了这个方法:
async Task AddAccountAsync(AccountModel model)
{
Account entity = CreateFromModel(model);
DbContext.Add(entity);
await DbContext.SaveChangesAsync();
model.Id = entity.Id;
}
运行后的model.Id(带有等待)是-9223372036854775808。
但如果我改用这个:
async Task<long> AddAccountAsync(AccountModel model)
{
Account entity = CreateFromModel(model);
DbContext.Add(entity);
await DbContext.SaveChangesAsync();
return entity.Id;
}
它返回 right 值。为什么会这样?
【问题讨论】:
-
所以如果你这样做:
var model = new AccountModel(); await AddAccountAsync(model); Console.WriteLine(model.Id);你会得到id == -9223372036854775808? -
是的,我有 id == -9223372036854775808
-
我想我的问题是,你怎么称呼
AddAccountAsync?调用代码看起来如何? -
@CodingYoshi 不正确:返回基本的
Task是完全正确的,你把它与async void签名混淆了,如果可能的话确实应该避免
标签: c# postgresql entity-framework-core npgsql