我正在尝试在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;,
答案 0 :(得分:1)
你的模特错了。由于您在Conversation
和User
之间存在N:N关系,因此您需要在ForeingKey
之前从对话中删除Members
属性,并且您需要添加ICollection<Conversation> Conversation
属性在User类中,或进一步使用FluentApi