代码之家  ›  专栏  ›  技术社区  ›  Hoàng Nguyễn

asp。net core/c#-检查具有两个主键的表中是否存在一行?

  •  0
  • Hoàng Nguyễn  · 技术社区  · 7 年前

    这是我在Microsoft SQL db中的表架构:

    [account_id](PK, FK, int, not null)
    [business_id](PK, FK, int, not null)
    [identifier](nvarchar(100), null)
    

    在向该表中添加新行之前,我想检查是否存在两个主键中的值相同的行。例如,我有一张桌子:

    account_id | business_id | identifier 
    _____________________________________    
             1 |           2 | abc
             2 |           3 | cdf
    

    现在我尝试不同的案例:

    context.add(account_id: 1, business_id: 3, identifier: null) => success
    context.add(account_id: 1, business_id: 2, identifier: null) => fail
    context.add(account_id: 2, business_id: 2, identifier: null) => success
    context.add(account_id: 3, business_id: 3, identifier: null) => success
    

    简而言之,我想检查是否已经存在一行,其中有两个主键与 account_id business_id ,否则,创建新行。

    这是我的代码,没有检查副本:

    [HttpPost("generate-identifier")]
    [ProducesResponseType(typeof(void), 204)]
    public IActionResult GenerateIdentifier(GenerateIdentifierRequest model)
    {
      if (!ModelState.IsValid) return BadRequest(GetValidationErrors(ModelState));
    
      BusinessAccount businessAccount = new BusinessAccount() {
        AccountId = GetCurrentUserId(),
        BusinessId = model.BusinessId,
        Identifier = model.Identifier
      };
    
      context.Add(businessAccount);
      context.SaveChanges();
    
      return NoContent();
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Hany Habib    7 年前

    有两个或两个以上主键的称为复合键。但是,不能使用“关键点”属性定义复合关键点。这只能通过Fluent API完成。但你似乎已经处理好了第一部分。

    对于第二部分,要检查记录是否可用,通常可以使用linq查询。任何()或。计数

    前任:

    var businessAccountCount = context.BusinessAccount.Count(a => a.AccountId == .. && a.business_id == ..);
    if(businessAccountCount > 0)
       return ....
    else
     {
        //Add your Entity & Return Created
     }