【发布时间】:2021-08-02 12:05:01
【问题描述】:
我正在创建一个 ASP.NET Core WEB API。
如果我在我的用户模型中包含一个构造函数,我会得到一个错误。而且我无法运行任何请求,例如 GET 用户请求。
关于我做错了什么的任何线索?我的模型中不允许有构造函数吗?如果没有,我还能做什么,因为我需要一种方法来在我的其他函数中以某种方式初始化新用户。
错误:
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: No suitable constructor was found for entity type 'User'. The following constructors had parameters that could not be bound to properties of the entity type: cannot bind 'u' in 'User(string u)'.
// USER MODEL
public class User
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserID { get; set; }
public string Username { get; set; }
public bool IsAdmin { get; set; }
public bool EmailNotifications { get; set; }
public User(string u) // THE CONSTRUCTOR IN QUESTION
{
this.UserID = 0;
this.Username = u;
this.IsAdmin = false;
this.EmailNotifications = false;
}
}
// GET: api/Users
[HttpGet]
public async Task<ActionResult<IEnumerable<User>>> GetUsers()
{
return await _context.Users.ToListAsync();
}
【问题讨论】:
-
添加默认构造函数。
-
我鼓励您再次阅读错误消息。这实际上是一个很好的错误消息,包含很多细节。
标签: c# asp.net asp.net-core asp.net-core-webapi