使用Entity Framework时出现InvalidCastException

时间:2016-02-21 23:21:44

标签: c# http entity-framework-5 asp.net-web-api2

我正在尝试在Conversation类中保存用户列表,但在执行POST时我收到InvalidCastException

这是我的用户类:

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

这是我的对话课程:

[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()
    {

    }
}

这是对话控制器:

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

修改 发表声明:

{
"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"}]
}

我得到的错误是:

  

&#34; ExceptionMessage&#34;:&#34;无法转换类型&System; System.Collections.Generic.List`1 [AcademicAssistant.Models.User]&#39;输入&#39; AcademicAssistant.Models.User&#39;。&#34;,

1 个答案:

答案 0 :(得分:1)

你的模特错了。由于您在ConversationUser之间存在N:N关系,因此您需要在ForeingKey之前从对话中删除Members属性,并且您需要添加ICollection<Conversation> Conversation属性在User类中,或进一步使用FluentApi

配置所需的关系