data/authors/Paul Logan.json

Override LINQ To SQL auto generated association names


After adding some missing FKs to a table in the database and refreshing the dbml file, the generated member names are not very informative and can be confusing.

For example, the StudentClassTransfer table records movement of students between classes. There is a FromClass and a ToClass, which is how I would like to refer to it in when coding. However, LINQ to SQL generates the names Class and Class1.

I could rename them in the dbml file, but these changes will be overwritten by LINQ to SQL the next time I modify the database and refresh the dbml file. Rather than fighting it, I will use a win-win approach.

Create a partial class definition for StudentClassTransfer and add my meaningful names there as getter properties for the LINQ to SQL generated member names.

The .dbml file:

<?xml version="1.0" encoding="utf-8"?><Database Name="YourDatabaseNameHere" Class="DBDataContext" xmlns="">
  <Connection Mode="WebSettings" ConnectionString="Data Source=YourDatabaseServerNameHere;Initial Catalog=YourDatabaseNameHere;Persist Security Info=True;User ID=YourUserID" SettingsObjectName="System.Configuration.ConfigurationManager.ConnectionStrings" SettingsPropertyName="YourConnectionString" Provider="System.Data.SqlClient" />
  <Table Name="dbo.StudentClassTransfer" Member="StudentClassTransfers">
    <Type Name="StudentClassTransfer">
      <Column Name="StudentClassTransferID" Type="System.Int32" DbType="Int NOT NULL IDENTITY" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />
      <Column Name="StudentID" Type="System.Int32" DbType="Int NOT NULL" CanBeNull="false" />
      <Column Name="FromClassID" Type="System.Int32" DbType="Int NOT NULL" CanBeNull="false" />
      <Column Name="ToClassID" Type="System.Int32" DbType="Int NOT NULL" CanBeNull="false" />
      <Column Name="TransferDate" Type="System.DateTime" DbType="DateTime NOT NULL" CanBeNull="false" />
      <Column Name="UserID" Type="System.Int32" DbType="Int NOT NULL" CanBeNull="false" />
      <Association Name="Class_StudentClassTransfer" Member="Class" ThisKey="FromClassID" OtherKey="ClassID" Type="Class" IsForeignKey="true" />
      <Association Name="Class_StudentClassTransfer1" Member="Class1" ThisKey="ToClassID" OtherKey="ClassID" Type="Class" IsForeignKey="true" />
      <Association Name="Student_StudentClassTransfer" Member="Student" ThisKey="StudentID" OtherKey="StudentID" Type="Student" IsForeignKey="true" />
      <Association Name="User_StudentClassTransfer" Member="User" ThisKey="UserID" OtherKey="UserID" Type="User" IsForeignKey="true" />

The StudentClassTransfer partial class:


    public partial class StudentClassTransfer
        public Class FromClass => this.Class;
        public Class ToClass => this.Class1;