ORM Designer (DBML) Overview
What is the ORM Designer?
The ORM Designer, also known as the .dbml
designer, provides a visual interface for building the object‑relational mapping between a SQL Server database and your .NET classes. It eliminates the need for hand‑written mapping code and keeps your data model in sync with the database schema.
Create a New LINQ to SQL Model
- In Visual Studio, choose Project ➔ Add New Item.
- Select LINQ to SQL Classes and name it
Northwind.dbml
. - The designer surface appears. Drag tables, views, and stored procedures from Server Explorer onto the surface.
// Example: Adding a Table to the designer programmatically
DataContext db = new DataContext(@"Server=.;Database=Northwind;Trusted_Connection=True;");
Table customers = db.GetTable<Customer>();
Mapping Customizations
After dragging a table onto the surface you can:
- Rename the generated entity class.
- Mark a column as the primary key, version, or association.
- Set
IsDbGenerated
andAutoSync
for identity columns.
// Example: Customizing a column attribute
[Column(Storage="_OrderID", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public int OrderID
{
get { return this._OrderID; }
set { if ((this._OrderID != value)) { this._OrderID = value; NotifyPropertyChanging("OrderID"); } }
}
Generated Code Overview
The designer creates a partial class that inherits from DataContext
. You can extend this class without modifying the generated file.
// NorthwindDataContext.designer.cs (auto‑generated)
public partial class NorthwindDataContext : DataContext
{
public Table<Customer> Customers;
public Table<Order> Orders;
// ... other tables
}
// NorthwindDataContext.cs (user code)
public partial class NorthwindDataContext
{
public IEnumerable<Customer> GetCustomersByCountry(string country)
{
return this.Customers.Where(c => c.Country == country);
}
}
Best Practices
- Keep the .dbml file under source control; it is the single source of truth for the model.
- Regenerate the code after any schema change and rebuild the solution.
- Use partial classes to add business logic without risking overwrites.
- Prefer
DataLoadOptions
for eager loading of related entities.