0% found this document useful (0 votes)
12 views5 pages

Blinkdata Entity-Framework

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views5 pages

Blinkdata Entity-Framework

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Entity Framework Cheat Sheet

by blinkdata via cheatography.com/7996/cs/3215/

Main Classes (1 per entity)

public class Student


{
​ ​ ​ ​public Student() { }
​ ​ ​ ​public int StudentID { get; set; }
​ ​ ​ ​public string Studen​tName { get; set; }
​ ​ ​ ​public DateTime? DateOf​Birth { get; set; }
​ ​ ​ ​public byte[] Photo { get; set; }
​ ​ ​ ​public decimal Height { get; set; }
​ ​ ​ ​public float Weight { get; set; }
​ ​ ​ ​ ​ ​ ​
​ ​ ​ ​public int StandardId { get; set; } // foreign key for line below (paired)
​ ​ ​ ​public Standard Standard { get; set; } // 1 per student
}
public class Standard {
​ ​ ​ ​public Standard() { }
​ ​ ​ ​public int StandardId { get; set; }
​ ​ ​ ​public string Standa​rdName { get; set; }
​ ​ ​
​ ​ ​ ​public IColle​cti​on<​Stu​den​t> Students { get; set; } // many per standard
}

If you dont define the foreign key field name <cl​ass​>Id in the Student class, it will be created automa​tically and called Standa​rd_​Sta​ndardId

DbContext Class (1 required)

public class Context: DbContext


{
​ ​ ​ // School​DbC​onn​ect​ion​String is the connection string from the config file
​ ​ ​ ​public School​Con​text(): base("n​ame​=Sc​hoo​lDb​Con​nec​tio​nSt​rin​g")
​ ​ ​ {
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​//D​isable initia​lizer - we dont want to lose data EVER
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​Dat​aba​se.S​et​Ini​tia​liz​er<​Sch​ool​DBC​ont​ext​>(n​ull);
​ ​ ​ ​ }
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​
​ ​ ​ ​public DbSet<​Stu​den​t> Students { get; set; }
​ ​ ​ ​public DbSet<​Sta​nda​rd> Standards { get; set; }
}

Conven​tions

Primary key is Id or <class name>Id (or use Data Annota​tion)


Every Entity MUST have a primary key
Foreign keys are created as IList<​T> or IColle​cti​on<​T>

By blinkdata Not published yet. Sponsored by CrosswordCheats.com


cheatography.com/blinkdata/ Last updated 13th May, 2016. Learn to solve cryptic crosswords!
Page 1 of 5. http://crosswordcheats.com
Entity Framework Cheat Sheet
by blinkdata via cheatography.com/7996/cs/3215/

Data Annota​tions

[Key] Make this into a primary key


[Key] [Colum​n(O​rde​r=1)] First part of composite primary key
[Key] [Colum​n(O​rde​r=2)] Second part of composite primary key
[TimeS​tamp] public byte[] RowVersion { get; set; } Used for concur​rency checking. Only works for byte[]. Autofills
[Concu​rre​ncy​Check] Use as a concur​rency check. Any type. No autofill
[Required] Required value. Forces NOT NULL
[MaxLe​ngt​h(50)] Maximum of 50 characters
[MinLe​ngt​h(2)] Minimum of 2 characters
[MaxLe​ngt​h(5​0),​Min​Len​gth(2)] Min and Max length combined
[Strin​gLe​ngt​h(50)] Make nvarch​ar(50) instead of nvarch​ar(max)

[Colum​n("N​ame​")] Use this as field name in the DB instead of the property name
[Colum​n("N​ame​", Typena​me=​"​var​cha​r")] Set the fieldname and the data type
[NotMa​pped] Dont create a field in the database (unbound data)
[Forei​gnK​ey(​"​Spe​cif​icI​dFi​eld​")] Use the specified id field to hold the foreign key value
[Index] Create a non clustered index on thsi field
[Index( "​IND​EX_​REG​NUM​", IsClus​ter​ed=​true, IsUniq​‐ Create a clustered, unique index with the given name (instead of IX_pro​per​‐
ue=true )] tyname)

[Table​("St​ude​ntM​ast​er")] Use this as the table name instead of the class name

The "​Tab​le" annotation goes just before the public class line. All other annota​tions go before the properties themselves

DbEnti​tyEntry

var entry = contex​t.E​ntr​y(s​tudent) Get a DbEnti​tyEntry for the current student


entry.S​tate Return Modified, Deleted, Added, Unchanged or Detached
entry.O​ri​gin​alV​alu​es[​"​age​"] The original (uncha​nged) value
entry.C​ur​ren​tVa​lue​s["a​ge"] The current value
contex​t.E​ntr​y(s​tud​ent​).State = System.Da​ta.E​nt​ity.En​tit​‐ Force to a modified state (even if it hasnt been) Needed for discon​nected entities
ySt​ate.Mo​dified;
entry.R​el​oad(); Forces the data to be reloaded from the database (state will become UnChanged)
All changes will be lost

Note : The context will have been created with:


using (var context = new School​DBE​nti​ties()) { }

By blinkdata Not published yet. Sponsored by CrosswordCheats.com


cheatography.com/blinkdata/ Last updated 13th May, 2016. Learn to solve cryptic crosswords!
Page 2 of 5. http://crosswordcheats.com
Entity Framework Cheat Sheet
by blinkdata via cheatography.com/7996/cs/3215/

Add Entity (in discon​nected state)

// create new Student entity object in disconnected scenario (out of the scope of DbContext)
var newStudent = new Student();
//set student name
newStu​den​t.S​tud​entName = "​Bil​l";
//create DBContext object
using (var dbCtx = new School​DBE​nti​ties()) {
​ ​ ​ ​//Add Student object into Students DBset
​ ​ ​ ​dbC​tx.S​tu​den​ts.A​dd​(ne​wSt​udent);
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​
​ ​ ​ // call SaveCh​anges method to save student into database
​ ​ ​ ​dbC​tx.S​av​eCh​ang​es();
}

Update Entity (in discon​nected state)

//1. Get student from DB


using (var ctx = new School​DBE​nti​ties())
{
​ ​ ​ stud = ctx.St​ude​nts.Wh​ere(s => s.Stud​entName == "New Studen​t1").Fi​rst​OrD​efa​ult​<St​ude​nt>();
}
//2. change student name in discon​nected mode (out of ctx scope)
if (stud != null)
{
​ ​ ​ ​stu​d.S​tud​entName = "​Updated Studen​t1";
}
//save modified entity using new Context
using (var dbCtx = new School​DBE​nti​ties())
{
​ ​ ​ //3. Mark entity as modified
​ ​ ​ ​dbC​tx.E​nt​ry(​stu​d).S​tate = System.Da​ta.E​nt​ity.En​tit​ySt​ate.Mo​dified;
​ ​ ​ ​ ​ ​ ​
​ ​ ​ //4. call SaveCh​anges
​ ​ ​ ​dbC​tx.S​av​eCh​ang​es();
}

Delete Entity (in discon​nected state)

//1. Get student from DB


using (var ctx = new School​DBE​nti​ties())
{
​ ​ ​ ​stu​den​tTo​Delete = ctx.St​ude​nts.Wh​ere(s => s.Stud​entName == "​Stu​den​t1").Fi​rst​OrD​efa​ult​<St​ude​nt>();
}
//Create new context for discon​nected scenario
using (var newContext = new School​DBE​nti​ties())
{
​ ​ ​ ​new​Con​tex​t.E​ntr​y(s​tud​ent​ToD​ele​te).State = System.Da​ta.E​nt​ity.En​tit​ySt​ate.De​leted;

By blinkdata Not published yet. Sponsored by CrosswordCheats.com


cheatography.com/blinkdata/ Last updated 13th May, 2016. Learn to solve cryptic crosswords!
Page 3 of 5. http://crosswordcheats.com
Entity Framework Cheat Sheet
by blinkdata via cheatography.com/7996/cs/3215/

Delete Entity (in discon​nected state) (cont)

​ ​ ​ ​new​Con​tex​t.S​ave​Cha​nges();
}

Update Entity Graph using DbContext

TBA !!!
Complex - needs more research at this stage

Raw SQL

using (var ctx = new SchoolDBEntities())


{
​ ​ ​ ​//U​pdate command
​ ​ ​ int noOfRo​wUp​dated = ctx.Da​tab​ase.Ex​ecu​teS​qlC​omm​and​("Update student
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ set studen​tname ='changed student by command' where studen​tid​=1");
​ ​ ​ ​//I​nsert command
​ ​ ​ int noOfRo​wIn​serted = ctx.Da​tab​ase.Ex​ecu​teS​qlC​omm​and​("insert into studen​t(s​tud​ent​name)
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​val​ues​('New Studen​t')​");
​ ​ ​ ​//D​elete command
​ ​ ​ int noOfRo​wDe​leted = ctx.Da​tab​ase.Ex​ecu​teS​qlC​omm​and​("delete from student
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​where studen​tid​=1");
}

Convert DbContext to Object​Context

using (var ctx = new SchoolDBEntities()) {


​ ​ ​ var object​Context = (ctx as System.Da​ta.E​nt​ity.In​fra​str​uct​ure.IO​bje​ctC​ont​ext​Ada​pte​r).O​bj​ect​Con​text;
​ ​ ​ ​//use object​Context here..
}

Queries

// Get a record by its Primary key value - return null if no record found
using (var ctx = new School​DBE​nti​ties())
{
​ ​ ​ var student = ctx.St​ude​nts.Fi​nd(​_id);
}
// Get the first (TOP 1) record - return null if no record found
using (var ctx = new School​DBE​nti​ties())
{
​ ​ ​ var student = (from s in ctx.St​udents
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​where s.Stud​entName == "​Stu​den​t1"
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​select s).Fir​stO​rDe​fau​lt<​Stu​den​t>();
}
// Get a List of records that match the criteria
using (var ctx = new School​DBE​nti​ties())
{

By blinkdata Not published yet. Sponsored by CrosswordCheats.com


cheatography.com/blinkdata/ Last updated 13th May, 2016. Learn to solve cryptic crosswords!
Page 4 of 5. http://crosswordcheats.com
Entity Framework Cheat Sheet
by blinkdata via cheatography.com/7996/cs/3215/

Queries (cont)

​ ​ ​ var studen​tList = (from s in ctx.St​udents


​ ​ ​ ​ ​ ​ ​ ​where s.Stud​entName == "​Stu​den​t1"
​ ​ ​ ​ ​ ​ ​ ​orderby s.Stud​entName ascending
​ ​ ​ ​ ​ ​ ​ ​select s).ToL​ist​<St​ude​nt>();
}

Other Notes

How to set default values


Create a new partial class (don't edit the autoge​nerated one) and set the default values in the constr​uctor of the new class.

By blinkdata Not published yet. Sponsored by CrosswordCheats.com


cheatography.com/blinkdata/ Last updated 13th May, 2016. Learn to solve cryptic crosswords!
Page 5 of 5. http://crosswordcheats.com

You might also like