Thursday, March 8, 2012

Entity Framwork - Insert Object


VB

Imports System.Data.Objects

 1)Dim context As New Entities
 2)Dim educationName As String = "English"
 3)Dim insertingObject As Education =
 4)context.Educations.FirstOrDefault(Function(c) c.EducationName = educationName)

 5) If insertingObject Is Nothing Then
 6)   Dim newEducation As New Education
 7)   newEducation.EducationName = "English"

 8)   newEducation.EducationDescription ="English Decription"        
 9)   context.Educations.AddObject(newEducation)
10)   Dim result = context.SaveChanges()
    End If


let see what abve code

Let’s say you want to insert new education into education table
Fist create object form current context
3,4 check the inserting object already exists  if not insert the object to Educations collections.
context.SaveChanges() means save modification to the data base permanently
Result >0 means no error successfully inserted.




C#

using System.Data.Objects


string educationName = "English";
Entities context = new Entities();

Education insertingObject = context.Educations.FirstOrDefault(c => c.EducationName == educationName);

if (insertingObject == null) {
 Education newEducation = new Education();
 newEducation.EducationName = "English";
 newEducation.EducationDescription = "English Decription";
 context.Educations.AddObject(newEducation);
 dynamic result = context.SaveChanges();
}

No comments: