DCSIMG
LINQ to SQL Classes - Gilad Lavian's Blog

Gilad Lavian's Blog

In Development

LINQ to SQL Classes

One can only wish everybody to speak LINQ!

 

The following solution demonstrate how to query database tables with object relational data classes. For this example you need to download and install the AdventureWorks Database provided by Microsoft.

 

First, create a new console project:

CraeteNewProject

 

 Open the "Server Explorer", click on the "Connect to Database" button:

ConnectToDB0

 

Select the Microsoft SQL Server:

ConnectToDB1

 

The next step is to connect to your AdventureWorks Database Server, from the

"Add Connection" window.

Select the appropriate Server and Database (AdventureWorks) and click OK.

After that, you should see the AdventureWorks.dbo in your Server Explorer window.

 

Now, lets create the "LINQ to SQL classes" file.

Go to your solution explorer and "Add->New Item". Select the "LINQ to SQL Classes" and name it AdventureWorks: 

 CreateLinkToSqlClasses

 

You should see now a new item in your solution explorer called "AdventureWorks.dbml".

Now you will notice that a new window for the AdventureWorks.dbml is opened.

This is the "Object Relation Designer", in here we going to drag and drop the selected tables we want to query.

 

The next thing we want to do is to drag our table, so lest expand the Tables tree under the root Database tree, and then drag and drop the Employee table to the AdventureWorks.dbml designer.

As you can see, you created an "Object Relation" to the table called Employee:

RelationData

 

What you don't see right now, is the amazing mechanism that generated a lots of code:

  • Employee Class, represents all the properties (columns)  in the Employee table.
  • A new methods for Inserting, Updating and Deleting an Employee.
    • InsertEmployee
    • UpdateEmployee
    • DeleteEmployee

You actually doing nothing and eventually getting a complete class equipped with every thing you just need to work on this table (Employee).

To see the complete code generated by this creation action, please open the AdventureWorks.designer.cs under the AdventureWorkds.dbml and be amazed yourself.

   1: //------------------------------------------------------------------------------
   2: // <auto-generated>
   3: //     This code was generated by a tool.
   4: //     Runtime Version:2.0.50727.1378
   5: //
   6: //     Changes to this file may cause incorrect behavior and will be lost if
   7: //     the code is regenerated.
   8: // </auto-generated>
   9: //------------------------------------------------------------------------------
  10:  
  11: namespace Practice.LINQ
  12: {
  13:     using System.Data.Linq;
  14:     using System.Data.Linq.Mapping;
  15:     using System.Data;
  16:     using System.Collections.Generic;
  17:     using System.Reflection;
  18:     using System.Linq;
  19:     using System.Linq.Expressions;
  20:     using System.ComponentModel;
  21:     using System;
  22:     
  23:     
  24:     [System.Data.Linq.Mapping.DatabaseAttribute(Name="AdventureWorks")]
  25:     public partial class AdventureWorksDataContext : System.Data.Linq.DataContext
  26:     {
  27:         
  28:         private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();
  29:         
  30:     #region Extensibility Method Definitions
  31:     partial void OnCreated();
  32:     partial void InsertEmployee(Employee instance);
  33:     partial void UpdateEmployee(Employee instance);
  34:     partial void DeleteEmployee(Employee instance);
  35:     #endregion
  36:         
  37:         static AdventureWorksDataContext()
  38:         {
  39:         }
  40:         
  41:         public AdventureWorksDataContext(string connection) : 
  42:                 base(connection, mappingSource)
  43:         {
  44:             OnCreated();
  45:         }
  46:         
  47:         public AdventureWorksDataContext(System.Data.IDbConnection connection) : 
  48:                 base(connection, mappingSource)
  49:         {
  50:             OnCreated();
  51:         }
  52:         
  53:         public AdventureWorksDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) : 
  54:                 base(connection, mappingSource)
  55:         {
  56:             OnCreated();
  57:         }
  58:         
  59:         public AdventureWorksDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) : 
  60:                 base(connection, mappingSource)
  61:         {
  62:             OnCreated();
  63:         }
  64:         
  65:         public AdventureWorksDataContext() : 
  66:                 base(global::Practice.LINQ.Properties.Settings.Default.AdventureWorksConnectionString, mappingSource)
  67:         {
  68:             OnCreated();
  69:         }
  70:         
  71:         public System.Data.Linq.Table<Employee> Employees
  72:         {
  73:             get
  74:             {
  75:                 return this.GetTable<Employee>();
  76:             }
  77:         }
  78:     }
  79:     
  80:     [Table(Name="HumanResources.Employee")]
  81:     public partial class Employee : INotifyPropertyChanging, INotifyPropertyChanged
  82:     {
  83:         
  84:         private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
  85:         
  86:         private int _EmployeeID;
  87:         
  88:         private string _NationalIDNumber;
  89:         
  90:         private int _ContactID;
  91:         
  92:         private string _LoginID;
  93:         
  94:         private System.Nullable<int> _ManagerID;
  95:         
  96:         private string _Title;
  97:         
  98:         private System.DateTime _BirthDate;
  99:         
 100:         private char _MaritalStatus;
 101:         
 102:         private char _Gender;
 103:         
 104:         private System.DateTime _HireDate;
 105:         
 106:         private bool _SalariedFlag;
 107:         
 108:         private short _VacationHours;
 109:         
 110:         private short _SickLeaveHours;
 111:         
 112:         private bool _CurrentFlag;
 113:         
 114:         private System.Guid _rowguid;
 115:         
 116:         private System.DateTime _ModifiedDate;
 117:         
 118:         private EntitySet<Employee> _Employees;
 119:         
 120:         private EntityRef<Employee> _Employee1;
 121:         
 122:     #region Extensibility Method Definitions
 123:     partial void OnLoaded();
 124:     partial void OnValidate();
 125:     partial void OnCreated();
 126:     partial void OnEmployeeIDChanging(int value);
 127:     partial void OnEmployeeIDChanged();
 128:     partial void OnNationalIDNumberChanging(string value);
 129:     partial void OnNationalIDNumberChanged();
 130:     partial void OnContactIDChanging(int value);
 131:     partial void OnContactIDChanged();
 132:     partial void OnLoginIDChanging(string value);
 133:     partial void OnLoginIDChanged();
 134:     partial void OnManagerIDChanging(System.Nullable<int> value);
 135:     partial void OnManagerIDChanged();
 136:     partial void OnTitleChanging(string value);
 137:     partial void OnTitleChanged();
 138:     partial void OnBirthDateChanging(System.DateTime value);
 139:     partial void OnBirthDateChanged();
 140:     partial void OnMaritalStatusChanging(char value);
 141:     partial void OnMaritalStatusChanged();
 142:     partial void OnGenderChanging(char value);
 143:     partial void OnGenderChanged();
 144:     partial void OnHireDateChanging(System.DateTime value);
 145:     partial void OnHireDateChanged();
 146:     partial void OnSalariedFlagChanging(bool value);
 147:     partial void OnSalariedFlagChanged();
 148:     partial void OnVacationHoursChanging(short value);
 149:     partial void OnVacationHoursChanged();
 150:     partial void OnSickLeaveHoursChanging(short value);
 151:     partial void OnSickLeaveHoursChanged();
 152:     partial void OnCurrentFlagChanging(bool value);
 153:     partial void OnCurrentFlagChanged();
 154:     partial void OnrowguidChanging(System.Guid value);
 155:     partial void OnrowguidChanged();
 156:     partial void OnModifiedDateChanging(System.DateTime value);
 157:     partial void OnModifiedDateChanged();
 158:     #endregion
 159:         
 160:         public Employee()
 161:         {
 162:             OnCreated();
 163:             this._Employees = new EntitySet<Employee>(new Action<Employee>(this.attach_Employees), new Action<Employee>(this.detach_Employees));
 164:             this._Employee1 = default(EntityRef<Employee>);
 165:         }
 166:         
 167:         [Column(Storage="_EmployeeID", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
 168:         public int EmployeeID
 169:         {
 170:             get
 171:             {
 172:                 return this._EmployeeID;
 173:             }
 174:             set
 175:             {
 176:                 if ((this._EmployeeID != value))
 177:                 {
 178:                     this.OnEmployeeIDChanging(value);
 179:                     this.SendPropertyChanging();
 180:                     this._EmployeeID = value;
 181:                     this.SendPropertyChanged("EmployeeID");
 182:                     this.OnEmployeeIDChanged();
 183:                 }
 184:             }
 185:         }
 186:         
 187:         [Column(Storage="_NationalIDNumber", DbType="NVarChar(15) NOT NULL", CanBeNull=false)]
 188:         public string NationalIDNumber
 189:         {
 190:             get
 191:             {
 192:                 return this._NationalIDNumber;
 193:             }
 194:             set
 195:             {
 196:                 if ((this._NationalIDNumber != value))
 197:                 {
 198:                     this.OnNationalIDNumberChanging(value);
 199:                     this.SendPropertyChanging();
 200:                     this._NationalIDNumber = value;
 201:                     this.SendPropertyChanged("NationalIDNumber");
 202:                     this.OnNationalIDNumberChanged();
 203:                 }
 204:             }
 205:         }
 206:         
 207:         [Column(Storage="_ContactID", DbType="Int NOT NULL")]
 208:         public int ContactID
 209:         {
 210:             get
 211:             {
 212:                 return this._ContactID;
 213:             }
 214:             set
 215:             {
 216:                 if ((this._ContactID != value))
 217:                 {
 218:                     this.OnContactIDChanging(value);
 219:                     this.SendPropertyChanging();
 220:                     this._ContactID = value;
 221:                     this.SendPropertyChanged("ContactID");
 222:                     this.OnContactIDChanged();
 223:                 }
 224:             }
 225:         }
 226:         
 227:         [Column(Storage="_LoginID", DbType="NVarChar(256) NOT NULL", CanBeNull=false)]
 228:         public string LoginID
 229:         {
 230:             get
 231:             {
 232:                 return this._LoginID;
 233:             }
 234:             set
 235:             {
 236:                 if ((this._LoginID != value))
 237:                 {
 238:                     this.OnLoginIDChanging(value);
 239:                     this.SendPropertyChanging();
 240:                     this._LoginID = value;
 241:                     this.SendPropertyChanged("LoginID");
 242:                     this.OnLoginIDChanged();
 243:                 }
 244:             }
 245:         }
 246:         
 247:         [Column(Storage="_ManagerID", DbType="Int")]
 248:         public System.Nullable<int> ManagerID
 249:         {
 250:             get
 251:             {
 252:                 return this._ManagerID;
 253:             }
 254:             set
 255:             {
 256:                 if ((this._ManagerID != value))
 257:                 {
 258:                     if (this._Employee1.HasLoadedOrAssignedValue)
 259:                     {
 260:                         throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
 261:                     }
 262:                     this.OnManagerIDChanging(value);
 263:                     this.SendPropertyChanging();
 264:                     this._ManagerID = value;
 265:                     this.SendPropertyChanged("ManagerID");
 266:                     this.OnManagerIDChanged();
 267:                 }
 268:             }
 269:         }
 270:         
 271:         [Column(Storage="_Title", DbType="NVarChar(50) NOT NULL", CanBeNull=false)]
 272:         public string Title
 273:         {
 274:             get
 275:             {
 276:                 return this._Title;
 277:             }
 278:             set
 279:             {
 280:                 if ((this._Title != value))
 281:                 {
 282:                     this.OnTitleChanging(value);
 283:                     this.SendPropertyChanging();
 284:                     this._Title = value;
 285:                     this.SendPropertyChanged("Title");
 286:                     this.OnTitleChanged();
 287:                 }
 288:             }
 289:         }
 290:         
 291:         [Column(Storage="_BirthDate", DbType="DateTime NOT NULL")]
 292:         public System.DateTime BirthDate
 293:         {
 294:             get
 295:             {
 296:                 return this._BirthDate;
 297:             }
 298:             set
 299:             {
 300:                 if ((this._BirthDate != value))
 301:                 {
 302:                     this.OnBirthDateChanging(value);
 303:                     this.SendPropertyChanging();
 304:                     this._BirthDate = value;
 305:                     this.SendPropertyChanged("BirthDate");
 306:                     this.OnBirthDateChanged();
 307:                 }
 308:             }
 309:         }
 310:         
 311:         [Column(Storage="_MaritalStatus", DbType="NChar(1) NOT NULL")]
 312:         public char MaritalStatus
 313:         {
 314:             get
 315:             {
 316:                 return this._MaritalStatus;
 317:             }
 318:             set
 319:             {
 320:                 if ((this._MaritalStatus != value))
 321:                 {
 322:                     this.OnMaritalStatusChanging(value);
 323:                     this.SendPropertyChanging();
 324:                     this._MaritalStatus = value;
 325:                     this.SendPropertyChanged("MaritalStatus");
 326:                     this.OnMaritalStatusChanged();
 327:                 }
 328:             }
 329:         }
 330:         
 331:         [Column(Storage="_Gender", DbType="NChar(1) NOT NULL")]
 332:         public char Gender
 333:         {
 334:             get
 335:             {
 336:                 return this._Gender;
 337:             }
 338:             set
 339:             {
 340:                 if ((this._Gender != value))
 341:                 {
 342:                     this.OnGenderChanging(value);
 343:                     this.SendPropertyChanging();
 344:                     this._Gender = value;
 345:                     this.SendPropertyChanged("Gender");
 346:                     this.OnGenderChanged();
 347:                 }
 348:             }
 349:         }
 350:         
 351:         [Column(Storage="_HireDate", DbType="DateTime NOT NULL")]
 352:         public System.DateTime HireDate
 353:         {
 354:             get
 355:             {
 356:                 return this._HireDate;
 357:             }
 358:             set
 359:             {
 360:                 if ((this._HireDate != value))
 361:                 {
 362:                     this.OnHireDateChanging(value);
 363:                     this.SendPropertyChanging();
 364:                     this._HireDate = value;
 365:                     this.SendPropertyChanged("HireDate");
 366:                     this.OnHireDateChanged();
 367:                 }
 368:             }
 369:         }
 370:         
 371:         [Column(Storage="_SalariedFlag", DbType="Bit NOT NULL")]
 372:         public bool SalariedFlag
 373:         {
 374:             get
 375:             {
 376:                 return this._SalariedFlag;
 377:             }
 378:             set
 379:             {
 380:                 if ((this._SalariedFlag != value))
 381:                 {
 382:                     this.OnSalariedFlagChanging(value);
 383:                     this.SendPropertyChanging();
 384:                     this._SalariedFlag = value;
 385:                     this.SendPropertyChanged("SalariedFlag");
 386:                     this.OnSalariedFlagChanged();
 387:                 }
 388:             }
 389:         }
 390:         
 391:         [Column(Storage="_VacationHours", DbType="SmallInt NOT NULL")]
 392:         public short VacationHours
 393:         {
 394:             get
 395:             {
 396:                 return this._VacationHours;
 397:             }
 398:             set
 399:             {
 400:                 if ((this._VacationHours != value))
 401:                 {
 402:                     this.OnVacationHoursChanging(value);
 403:                     this.SendPropertyChanging();
 404:                     this._VacationHours = value;
 405:                     this.SendPropertyChanged("VacationHours");
 406:                     this.OnVacationHoursChanged();
 407:                 }
 408:             }
 409:         }
 410:         
 411:         [Column(Storage="_SickLeaveHours", DbType="SmallInt NOT NULL")]
 412:         public short SickLeaveHours
 413:         {
 414:             get
 415:             {
 416:                 return this._SickLeaveHours;
 417:             }
 418:             set
 419:             {
 420:                 if ((this._SickLeaveHours != value))
 421:                 {
 422:                     this.OnSickLeaveHoursChanging(value);
 423:                     this.SendPropertyChanging();
 424:                     this._SickLeaveHours = value;
 425:                     this.SendPropertyChanged("SickLeaveHours");
 426:                     this.OnSickLeaveHoursChanged();
 427:                 }
 428:             }
 429:         }
 430:         
 431:         [Column(Storage="_CurrentFlag", DbType="Bit NOT NULL")]
 432:         public bool CurrentFlag
 433:         {
 434:             get
 435:             {
 436:                 return this._CurrentFlag;
 437:             }
 438:             set
 439:             {
 440:                 if ((this._CurrentFlag != value))
 441:                 {
 442:                     this.OnCurrentFlagChanging(value);
 443:                     this.SendPropertyChanging();
 444:                     this._CurrentFlag = value;
 445:                     this.SendPropertyChanged("CurrentFlag");
 446:                     this.OnCurrentFlagChanged();
 447:                 }
 448:             }
 449:         }
 450:         
 451:         [Column(Storage="_rowguid", DbType="UniqueIdentifier NOT NULL")]
 452:         public System.Guid rowguid
 453:         {
 454:             get
 455:             {
 456:                 return this._rowguid;
 457:             }
 458:             set
 459:             {
 460:                 if ((this._rowguid != value))
 461:                 {
 462:                     this.OnrowguidChanging(value);
 463:                     this.SendPropertyChanging();
 464:                     this._rowguid = value;
 465:                     this.SendPropertyChanged("rowguid");
 466:                     this.OnrowguidChanged();
 467:                 }
 468:             }
 469:         }
 470:         
 471:         [Column(Storage="_ModifiedDate", DbType="DateTime NOT NULL")]
 472:         public System.DateTime ModifiedDate
 473:         {
 474:             get
 475:             {
 476:                 return this._ModifiedDate;
 477:             }
 478:             set
 479:             {
 480:                 if ((this._ModifiedDate != value))
 481:                 {
 482:                     this.OnModifiedDateChanging(value);
 483:                     this.SendPropertyChanging();
 484:                     this._ModifiedDate = value;
 485:                     this.SendPropertyChanged("ModifiedDate");
 486:                     this.OnModifiedDateChanged();
 487:                 }
 488:             }
 489:         }
 490:         
 491:         [Association(Name="Employee_Employee", Storage="_Employees", OtherKey="ManagerID")]
 492:         public EntitySet<Employee> Employees
 493:         {
 494:             get
 495:             {
 496:                 return this._Employees;
 497:             }
 498:             set
 499:             {
 500:                 this._Employees.Assign(value);
 501:             }
 502:         }
 503:         
 504:         [Association(Name="Employee_Employee", Storage="_Employee1", ThisKey="ManagerID", IsForeignKey=true)]
 505:         public Employee Employee1
 506:         {
 507:             get
 508:             {
 509:                 return this._Employee1.Entity;
 510:             }
 511:             set
 512:             {
 513:                 Employee previousValue = this._Employee1.Entity;
 514:                 if (((previousValue != value) 
 515:                             || (this._Employee1.HasLoadedOrAssignedValue == false)))
 516:                 {
 517:                     this.SendPropertyChanging();
 518:                     if ((previousValue != null))
 519:                     {
 520:                         this._Employee1.Entity = null;
 521:                         previousValue.Employees.Remove(this);
 522:                     }
 523:                     this._Employee1.Entity = value;
 524:                     if ((value != null))
 525:                     {
 526:                         value.Employees.Add(this);
 527:                         this._ManagerID = value.EmployeeID;
 528:                     }
 529:                     else
 530:                     {
 531:                         this._ManagerID = default(Nullable<int>);
 532:                     }
 533:                     this.SendPropertyChanged("Employee1");
 534:                 }
 535:             }
 536:         }
 537:         
 538:         public event PropertyChangingEventHandler PropertyChanging;
 539:         
 540:         public event PropertyChangedEventHandler PropertyChanged;
 541:         
 542:         protected virtual void SendPropertyChanging()
 543:         {
 544:             if ((this.PropertyChanging != null))
 545:             {
 546:                 this.PropertyChanging(this, emptyChangingEventArgs);
 547:             }
 548:         }
 549:         
 550:         protected virtual void SendPropertyChanged(String propertyName)
 551:         {
 552:             if ((this.PropertyChanged != null))
 553:             {
 554:                 this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
 555:             }
 556:         }
 557:         
 558:         private void attach_Employees(Employee entity)
 559:         {
 560:             this.SendPropertyChanging();
 561:             entity.Employee1 = this;
 562:             this.SendPropertyChanged("Employees");
 563:         }
 564:         
 565:         private void detach_Employees(Employee entity)
 566:         {
 567:             this.SendPropertyChanging();
 568:             entity.Employee1 = null;
 569:             this.SendPropertyChanged("Employees");
 570:         }
 571:     }
 572: }

 

Now, here comes the fun!

A simple query that select all the employees from the Employees table, but of course, by the relation object data class we just created.

 

In the Program.cs class, inside the static Main entry point function, add the following code and behold the magic:

   1: AdventureWorksDataContext db = new AdventureWorksDataContext();
   2:  
   3: var employees = from e in db.Employees 
   4:                 select e;
   5:  
   6: foreach (Employee emp in employees)
   7: {
   8:     Console.WriteLine(emp.Title);
   9: }
  10:  
  11: Console.ReadKey();

 

This is unbelievable, I didn't imagine to myself that its going to be so easy to query tables!

I never would have thought that it will come to that simplicity.

תוכן התגובה

Gilad Lavian כתב/ה:

I guess there’s a few ways to attack this situation.

But, I will use LINQ for the benefits it provides and the ease of the language.

# November 1, 2007 1:58 PM
שלח תגובה

(שדה חובה)  

(שדה חובה)  

(אופציונלי)

(שדה חובה) 

Please add 8 and 4 and type the answer here:


Enter the numbers above: