gpt4 book ai didi

c# - Web api中的重复键问题

转载 作者:可可西里 更新时间:2023-11-01 17:34:31 24 4
gpt4 key购买 nike

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

"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.",

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

session 类:

[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; }
}

我的 Controller 定义为:

发布:

 [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.",

最佳答案

问题是……

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);

关于c# - Web api中的重复键问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35542393/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com