【问题标题】:Is there a way to override the empty constructor in a class generated by LINQtoSQL?有没有办法覆盖 LINQtoSQL 生成的类中的空构造函数?
【发布时间】:2010-09-10 02:11:34
【问题描述】:

如果我的数据库中有一个名为“Users”的表,则会有一个由 LINQtoSQL 生成的名为“User”的类,该类已声明为空的构造函数。

如果我想重写这个构造函数并向它添加我自己的逻辑,最好的做法是什么?

【问题讨论】:

    标签: c# .net linq linq-to-sql


    【解决方案1】:

    由 O/R-Designer 生成的默认构造函数调用名为 OnCreated 的部分函数 - 因此最佳实践不是覆盖默认构造函数,而是在 @987654323 中实现部分函数 OnCreated @初始化项目:

    partial void OnCreated()
    {
      Name = "";
    }
    

    如果您正在实现其他构造函数,请始终注意调用默认构造函数,以便正确初始化类 - 例如,在默认构造函数中构造实体集(关系)。

    【讨论】:

      【解决方案2】:

      看起来你不能覆盖空的构造函数。相反,我会创建一个方法来执行您在空构造函数中需要的功能并返回新对象。

      // 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;
        }
      }
      

      然后在代码的其他地方,不要使用默认的空构造函数,而是执行以下操作之一:

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

      【讨论】:

        【解决方案3】:

        将 DataContext Connection 属性设置为“无”对我有用。步骤如下。

        打开 dbml -> 右键单击​​属性 -> 将 DataContext 属性中的连接更新为“无”。这将从生成的代码文件中删除空构造函数。 -> 使用如下所示的空构造函数为 DataContext 创建一个新的部分类

        Partial Class MyDataContext    
            Public Sub New()             
                MyBase.New(ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString, mappingSource)
                OnCreated()    
            End Sub    
        End Class
        

        【讨论】:

          【解决方案4】:

          这是 C# 版本:

          public partial class PENCILS_LinqToSql_DataClassesDataContext
          {
               public PENCILS_LinqToSql_DataClassesDataContext() : base(ConnectionString(), mappingSource)
              {
              }
          
              public static String ConnectionString()
              {
                  String CS;
                  String Key;
          
                  Key = System.Configuration.ConfigurationManager.AppSettings["DefaultConnectionString"].ToString();
          
                  /// Get the actual connection string.
                  CS = System.Configuration.ConfigurationManager.ConnectionStrings[Key].ToString();
          
                  return CS;
              }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-07-07
            • 1970-01-01
            • 2023-03-18
            • 2010-11-22
            • 2011-11-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多