Is there a way to override the empty constructor in a class generated by LINQtoSQL?

前端 未结 4 469
太阳男子
太阳男子 2021-01-17 17:49

If I have a table in my database called \'Users\', there will be a class generated by LINQtoSQL called \'User\' with an already declared empty constructor.

What is t

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-17 18:31

    It doesn't look like you can override the empty constructor. Instead, I would create a method that performs the functionality that you need in the empty constructor and returns the new object.

    // Add new partial class to extend functionality
    public partial class User {
    
      // Add additional constructor
      public User(int id) {
        ID = id;
      }
    
      // Add static method to initialize new object
      public User GetNewUser() {
        // functionality
        User user = new User();
        user.Name = "NewName";
        return user;
      }
    }
    

    Then elsewhere in your code, instead of using the default empty constructor, do one of the following:

    User user1 = new User(1);
    User user2 = User.GetNewUser();
    

提交回复
热议问题