InvalidCastException when using Entity Framework

2019-07-22 05:11发布

问题:

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

回答1:

Your model is wrong. As you have a N:N relationship between Conversation and User you need to remove ForeingKey attribute from conversation before Members, and you need to add ICollection<Conversation> Conversation property in User class, or go further and configure the relationship as you need with FluentApi