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

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

What is the best practice if I want to override this constructor and add my own logic to it?

+9
c # linq linq-to-sql
Sep 17 '08 at 12:11
source share
3 answers

The default constructor that O / R-Designer generates calls the OnCreate partial function - so it’s best not to override the default constructor, but instead implement the OnCreated partial function in MyDataClasses.cs to initialize the elements

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

If you implement other constructors, always be careful to call the default constructor so that classes are initialized correctly - for example, entities (relationships) are built in the default constructor.

+11
Sep 17 '08 at 14:30
source share

It doesn't look like you can override an empty constructor. Instead, I would create a method that performs the necessary functions in an empty constructor and returns a 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, in another place in your code, instead of using the empty default constructor, do one of the following:

 User user1 = new User(1); User user2 = User.GetNewUser(); 
+3
Sep 17 '08 at 12:17
source share

Setting the DataContext Connection property to "None" worked for me. Steps below.

Open dbml -> Right Click Properties -> Update Connection in the DataContext properties to No. This will remove the empty constructor from the generated code file. β†’ Create a new incomplete class for the DataContext with an empty constructor, as shown below

 Partial Class MyDataContext Public Sub New() MyBase.New(ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString, mappingSource) OnCreated() End Sub End Class 
+1
Apr 08 '14 at 11:39 on
source share