gpt4 book ai didi

c# - 使用 Entity Framework 时出现 InvalidCastException

转载 作者:可可西里 更新时间:2023-11-01 17:34:31 25 4
gpt4 key购买 nike

我试图在对话类中保存用户列表,但在执行 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;
}
}

这是我的 session 课:

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

}
}

这是对话 Controller :

发布:

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

获取:

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

我得到的错误是:

"ExceptionMessage": "Unable to cast object of type 'System.Collections.Generic.List`1[AcademicAssistant.Models.User]' to type 'AcademicAssistant.Models.User'.",

最佳答案

你的模型是错误的。由于您在 Conversation 之间存在 N:N 关系和 User你需要删除 ForeingKey Members 之前对话的属性, 你需要添加 ICollection<Conversation> Conversation User 类中的属性,或者进一步根据需要使用 FluentApi 配置关系

关于c# - 使用 Entity Framework 时出现 InvalidCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35543433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com