检查 Azure 函数中是否存在记录 (C#)

Checking if record exists in Azure Function (C#)

我想弄清楚如何在使用 Azure 函数中的 BindAsync 添加记录之前检查记录是否存在。有没有办法使用我现有的实现来执行此操作,还是我需要使用其他方法?

具体查看"output"局部变量周围的函数底部。

[FunctionName("Signup")]
public static async Task<IActionResult> Signup([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route ="user/signup")] HttpRequest Req, Binder binder, ILogger log)
{
    var UserId = System.Guid.NewGuid().ToString();
    var FirstName = Req.Form["FirstName"];
    var LastName = Req.Form["LastName"];
    string FbId = null;
    if (Req.Form.ContainsKey("FbId"))
    {
        FbId = Req.Form["FbId"];
    }
    var Email = Req.Form["Email"];
    var PasswordPlain = Req.Form["Password"];
    string hash;
    hash = BCrypt.Net.BCrypt.HashPassword(PasswordPlain);

    var ProfilePic = Req.Form.Files.GetFile("ProfilePic");
    var ProfilePicStream = ProfilePic.OpenReadStream();
    var ProfilePicFileName = await UploadImage(ProfilePicStream, UserId, binder);

    if (FbId == null)
    {
        log.LogInformation("No FB detected");
    }
    else
    {
        log.LogInformation("FB detected");
    }
    var NewUser = new UserTableEntity
    {
        PartitionKey = 1.ToString(),
        RowKey = UserId,
        FirstName = FirstName,
        LastName = LastName,
        FbId = FbId,
        Email = Email,
        ProfilePic = ProfilePicFileName,
        Password = hash
    };

    var attributes = new System.Attribute[]
    {
        new StorageAccountAttribute("TabbrDevCosmosDb"),
        new TableAttribute("Users")
    };

    var output = await binder.BindAsync<IAsyncCollector<UserTableEntity>>(attributes);
    await output.AddAsync(NewUser);
    return new OkObjectResult(JsonConvert.SerializeObject(NewUser));
}  

我们必须按照基本的方式进行,执行查询以查找是否有记录重复。

为查询添加声明式Table 输入绑定

public static async Task<IActionResult> Signup(
    [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "user/signup")] HttpRequest Req, 
    [Table("Users", Connection = "TabbrDevCosmosDb")]CloudTable table, 
    Binder binder, ILogger log)

执行查询,以Email为例

TableQuery<UserTableEntity> existQuery = new TableQuery<UserTableEntity>().Where(
    TableQuery.GenerateFilterCondition("Email", QueryComparisons.Equal, Email));

var queryResult = table.ExecuteQuerySegmentedAsync(existQuery, null).Result.Results;

if (queryResult.Count == 0)
{
    var attributes = new System.Attribute[]
    {
        new StorageAccountAttribute("TabbrDevCosmosDb"),
        new TableAttribute("Users")
    };
    var output = await binder.BindAsync<IAsyncCollector<UserTableEntity>>(attributes);
    await output.AddAsync(NewUser);
    return new OkObjectResult(JsonConvert.SerializeObject(NewUser));
}
else
{
    return new BadRequestObjectResult("Already exists");
}