Friday, January 28, 2011

Linq to SQL Mapping by decorating classes with special attributes


With LINQ to SQL, you can set up mappings between C# classes and an implied database schema either
by decorating the classes with special attributes or by writing an XML.

Following is a c# 4.0 code that describes first approach i.e. Linq to Sql mapping by decorating classes with special attributes.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq.Mapping;
using System.Data.Linq;

[Table(Name="Jobs")] public class Job
{
[Column(IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.OnInsert)]
internal int JobID { get; set; }
[Column] public string JobTitle { get; set; }
[Column] public long Salary { get; set; }
}

[Table(Name="Applications")] public class Application
{
[Column(IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.OnInsert)]
internal int ApplicationID { get; set; }
[Column] public int JobID  { get; set; }
[Column] public DateTime DateApplied { get; set; }
}

String ConStr=”"Data Source=localhost;Initial Catalog=JobsDB;Integrated Security=SSPI;"
DataContext dc = new DataContext(connectionString); // Get a live DataContext
dc.GetTable<Job>(); // Tells dc it's responsible for persisting the class Job
dc.GetTable<Application>(); // Tells dc it's responsible for persisting the class Application
dc.CreateDatabase(); // Causes dc to issue CREATE TABLE commands for each class

Above code will create JobsDB along with tables Jobs and Applications.


No comments:

Post a Comment