I am trying to inset a User into a Conversation Table. A conversation has a set collection of Users as a member variable. It is this variable that is giving me trouble. When I try to Post a Conversation I am getting the error:
"ExceptionMessage": "Violation of PRIMARY KEY constraint 'PK_dbo.Users'.
Cannot insert duplicate key in object 'dbo.Users'.
The duplicate key value is([email protected]).\r\nThe statement has been terminated.",
I am trying to insert an existing User into a Conversation but it looks like it is trying to insert a new User which is causing a duplicate error.
Conversation class:
[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;
}
}
The User is defined as:
public class User
{
[Key]
[DataMember]
public String Email { get; set; }
[DataMember]
public String Password { get; set; }
[DataMember]
public Boolean Admin { get; set; }
}
My controller is defined as:
POST:
[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);
}
GET:
[HttpGet]
public async Task<IHttpActionResult> GetConversation(String key)
{
Conversation convo = await db.Conversations.FindAsync(key);
if (convo == null)
{
return NotFound();
}
return Ok(convo);
}
Any input would be appreciated! :)
EDIT I never included the outter exception:
"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.",