【问题标题】:Error when there's a constructor in Model class模型类中有构造函数时出错
【发布时间】: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


【解决方案1】:

您需要提供一个默认构造函数,因为 EF 在您的情况下正在寻找一个默认的无参数构造函数。

// 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() { // you are missing this one

    }

    public User(string u) // THE CONSTRUCTOR IN QUESTION
    {
        this.UserID = 0;
        this.Username = u;
        this.IsAdmin = false;
        this.EmailNotifications = false;

    }

}

【讨论】:

  • ...或具有作为参数的属性。
猜你喜欢
  • 1970-01-01
  • 2018-08-24
  • 1970-01-01
  • 1970-01-01
  • 2022-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多