Web API 中的重复密钥问题

本文关键字:密钥 问题 API Web | 更新日期: 2023-09-27 18:35:33

>我正在尝试将用户插入对话表。对话具有一组用户作为成员变量。正是这个变量给我带来了麻烦。当我尝试发布对话时,出现错误:

"ExceptionMessage": "Violation of PRIMARY KEY constraint 'PK_dbo.Users'.
Cannot insert duplicate key in object 'dbo.Users'. 
The duplicate key value is(test@emailadd.com).'r'nThe statement has been terminated.",

我正在尝试将现有用户插入对话,但看起来它正在尝试插入导致重复错误的新用户。

会话课:

[DataContract]
public class Conversation
{
    [Key]
    [DataMember]
    public string Key { get; set; }
    [DataMember]
    public string ConversationName { get; set; }
    [DataMember]
    public string Administrator { get; set; }
    [DataMember]
    public List<User> Members { get; set; }
    public Conversation(string key, string name, string admin, List<User> members)
    {
        Key = key;
        ConversationName = name;
        Administrator = admin;
        Members = members;
    }
}

用户定义为:

public class User
{
    [Key]
    [DataMember]
    public String Email { get; set; }
    [DataMember]
    public String Password { get; set; }
    [DataMember]
    public Boolean Admin { get; set; }
}

我的控制器定义为:

发布:

 [HttpPost]
 public async Task<IHttpActionResult> PostConversation(Conversation convo)
 {
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
    db.Conversations.Add(convo);
    await db.SaveChangesAsync();
    return CreatedAtRoute("DefaultApi", new { name = convo.Key }, convo);
 }

获取:

[HttpGet]
public async Task<IHttpActionResult> GetConversation(String key)
{
    Conversation convo = await db.Conversations.FindAsync(key);
    if (convo == null)
    {
        return NotFound();
    }
    return Ok(convo);
}

任何意见将不胜感激! :)

编辑我从未包括外部例外:

"ExceptionMessage": "An error occurred while saving entities that do not expose foreign key properties for their relationships. 
The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. 
Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. 
See the InnerException for details.",

Web API 中的重复密钥问题

问题是...

db.Conversations.Add(convo);

。递归地将属于convo的所有实体标记为Added(当它们尚未附加到上下文时)。因此,它尝试插入新的User记录,而不仅仅是将外键设置为现有记录。

解决方案是在添加对话之前将User附加到上下文:

foreach(var user in convo.Members)
{
     db.Entry(user).State = System.Data.Entity.EntityState.Unchanged;
}
db.Conversations.Add(convo);

问题是:看起来您的密钥不是唯一的

确保使用 注释主键列键

[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]

它基本上告诉 ef 密钥是由 db 生成的

或者

添加使用 Id 的其他列,该列使用先前声明的注释动态生成