I am trying to save a List of Users in a Conversation class but I am getting an InvalidCastException
when performing a POST.
This is my User class:
public class User
{
[Key]
[DataMember]
public String Email { get; set; }
[DataMember]
public String Password { get; set; }
[DataMember]
public Boolean Admin { get; set; }
public User(String email, String password, Boolean admin)
{
Email = email;
Password = password;
Admin = admin;
}
}
And this is my 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]
[ForeignKey("Email")]
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 Conversation()
{
}
}
This is the Conversation controller:
POST:
[HttpPost]
public async Task<IHttpActionResult> PostConversation(Conversation convo)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
foreach (var user in convo.Members)
{
db.Entry(user).State = EntityState.Unchanged;
}
db.Conversations.Add(convo);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { name = convo.Key }, convo);
}
GET:
[HttpGet]
public IQueryable<Conversation> GetConversations()
{
return db.Conversations;
}
EDIT Post statement:
{
"Key": "123",
"ConversationName": "Test",
"Administrator": "Ken",
"Members": [{"Email": "y@12.com","Password" : "Passw-1", "Admin" : "true"},
{"Email": "y@123.com","Password" : "Passw-1", "Admin" : "false"}]
}
The error I am getting is:
"ExceptionMessage": "Unable to cast object of type 'System.Collections.Generic.List`1[AcademicAssistant.Models.User]' to type 'AcademicAssistant.Models.User'.",
Your model is wrong. As you have a N:N relationship between
Conversation
andUser
you need to removeForeingKey
attribute from conversation beforeMembers
, and you need to addICollection<Conversation> Conversation
property in User class, or go further and configure the relationship as you need with FluentApi