C# asp.net-core/c-检查具有2个主键的表中是否存在行?

C# asp.net-core/c-检查具有2个主键的表中是否存在行?,c#,sql,sql-server,asp.net-core,C#,Sql,Sql Server,Asp.net Core,这是我在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 __________________________________

这是我在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();
}

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

对于检查记录是否可用的第二部分,您通常可以使用.Any或.Count使用linq查询

例:


这肯定是一个具有复合主键的表吗?我很确定你不能有多个主键?你在使用EntityFramework吗?@john:是的,这是一种复合主键,然后可以有多个,这是我现在数据库中的一个实际表。是的,我也使用EF。一个表只能有一个主键。但是,也可以使用备用键。很好,请尝试告诉我var businessAccountCount显示错误运算符“&&”不能应用于“bool”和“int”类型的操作数对不起,它应该是==将更新它,近似错误的类型在主键中应该有两列或更多列称为复合键。在主键中还是作为主键?
var businessAccountCount = context.BusinessAccount.Count(a => a.AccountId == .. && a.business_id == ..);
if(businessAccountCount > 0)
   return ....
else
 {
    //Add your Entity & Return Created
 }