Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding new methods to LINQ to SQL generated classes

I am new to LINQ. I just dragged all my database tables onto the designer in a LINQ to SQL dbml. All my relationships are correct and look nice in the designer. I am able to pull data using simple LINQ code. I want to add my own methods now but don't want to blow away my changes if (when) I need to regenerate my dbml. I am guessing I just create a new class file and setup partial classes of the generated classes. Is this correct? For example, I have a generated class called SystemUser which contains the columns SystemUserId, Username, Password, PersonId, SecurityQuestionId, SecurityQuestionResponse. I want to add a method called void Authenticate() and a new property called bool Authenticated. Basically I want to pass in a username and password to Authenticate() and set the Authenticated property based on finding a matching user, etc. Where and how would I do this?

like image 464
user64874 Avatar asked Feb 11 '09 02:02

user64874


3 Answers

The LINQ-generated classes are partial classes, meaning you can extend them by creating your own partial classes or partial methods.

In your case, you can create a partial class for your SystemUser, and then add your method(s) in there. They will not be overwritten if the DBML file is regenerated.

Something like:

public partial class SystemUser
{
    public bool Authenticated { get; set; }

    void Authenticate()
    {
        //Perform custom logic here.
    }
}
like image 123
Eric King Avatar answered Sep 23 '22 01:09

Eric King


Take a look at using a Partial class... it might fit your situation very nicely.

like image 26
Brandon Avatar answered Sep 23 '22 01:09

Brandon


If you just want your class to have a new method you are correct create a new file and use partial class.

like image 39
Aaron Fischer Avatar answered Sep 26 '22 01:09

Aaron Fischer