Code Stash II

Squirrel Nuts
Jonathan Purdom
03 Mar 2016

Entity Framework Cheatsheet

Below are steps to create a new Entity Framework Library

  • Create a new Project in Visual Studion C# Library
  • Open the Nuget Package Console Enter Install-Package EntityFramework
  • Right Click Solution Explorer Choose Add >> New Item >> ADO.NET Entity Data Model
  • Enter a name for the Model e.g. Designer
  • Click Next

Link to Existing Database

  • Choose EF Designer from Database
  • Select New Connection >> Enter DB Credentials
  • Tick the Checkbox to Save connection string in App.Config
  • Click Next, Select Tables, Views, Stored Procedure
  • Click Finish to Create Model
  • A New Model will be shown called Designer.edmx
  • Example Code using the Database Context

Code Snippet Using Context

using (var context = new SSReportsEntities())
{ var deviceEntity = context.tblEquipments;
var firstDevice = deviceEntity.FirstOrDefault<tblEquipment>();
if (firstDevice != null)
{
firstDevice.ItemCode = "N012";
context.SaveChanges();
}}

Code First Example

public class Student
{
public Student(){}
public int StudentID { get; set; }
public string StudentName { get; set; }
public DateTime DateOfBirth { get; set; }

public Standard Standard { get; set; }
}

public class Standard
{
public Standard(){}
public int StandardId { get; set; }
public string StandardName { get; set; }
public ICollection<Student> Students { get; set; }

}

class Program
{
static void Main(string[] args)
{

using (var ctx = new SchoolContext())
{
Student stud = new Student() { StudentName = "New Student" };

ctx.Students.Add(stud);
ctx.SaveChanges();
}}}

SQL Stored Procedure Syntax

CREATE PROCEDURE usp_SampleStoredProcedure

@InputOne INT NOT NULL ,
@InputTwo VARCHAR(150) NULL,
@InputThree BIT = 0
AS
BEGIN
SET NOCOUNT ON;

DECLARE @SampleTable TABLE(
ID INT IDENTITY (100,1) NOT NULL,
FieldOne INT NOT NULL,
FieldTwo VARCHAR(150) NULL,
FieldThree BIT NOT NULL)

INSERT INTO @SampleTable (FieldOne,FieldTwo,FieldThree)
VALUES (@InputOne,@InputTwo, @InputThree)

RETURN @@Identity
END
GO