\documentclass[10pt,a4paper]{article} % Packages \usepackage{fancyhdr} % For header and footer \usepackage{multicol} % Allows multicols in tables \usepackage{tabularx} % Intelligent column widths \usepackage{tabulary} % Used in header and footer \usepackage{hhline} % Border under tables \usepackage{graphicx} % For images \usepackage{xcolor} % For hex colours %\usepackage[utf8x]{inputenc} % For unicode character support \usepackage[T1]{fontenc} % Without this we get weird character replacements \usepackage{colortbl} % For coloured tables \usepackage{setspace} % For line height \usepackage{lastpage} % Needed for total page number \usepackage{seqsplit} % Splits long words. %\usepackage{opensans} % Can't make this work so far. Shame. Would be lovely. \usepackage[normalem]{ulem} % For underlining links % Most of the following are not required for the majority % of cheat sheets but are needed for some symbol support. \usepackage{amsmath} % Symbols \usepackage{MnSymbol} % Symbols \usepackage{wasysym} % Symbols %\usepackage[english,german,french,spanish,italian]{babel} % Languages % Document Info \author{blinkdata} \pdfinfo{ /Title (entity-framework.pdf) /Creator (Cheatography) /Author (blinkdata) /Subject (Entity Framework Cheat Sheet) } % Lengths and widths \addtolength{\textwidth}{6cm} \addtolength{\textheight}{-1cm} \addtolength{\hoffset}{-3cm} \addtolength{\voffset}{-2cm} \setlength{\tabcolsep}{0.2cm} % Space between columns \setlength{\headsep}{-12pt} % Reduce space between header and content \setlength{\headheight}{85pt} % If less, LaTeX automatically increases it \renewcommand{\footrulewidth}{0pt} % Remove footer line \renewcommand{\headrulewidth}{0pt} % Remove header line \renewcommand{\seqinsert}{\ifmmode\allowbreak\else\-\fi} % Hyphens in seqsplit % This two commands together give roughly % the right line height in the tables \renewcommand{\arraystretch}{1.3} \onehalfspacing % Commands \newcommand{\SetRowColor}[1]{\noalign{\gdef\RowColorName{#1}}\rowcolor{\RowColorName}} % Shortcut for row colour \newcommand{\mymulticolumn}[3]{\multicolumn{#1}{>{\columncolor{\RowColorName}}#2}{#3}} % For coloured multi-cols \newcolumntype{x}[1]{>{\raggedright}p{#1}} % New column types for ragged-right paragraph columns \newcommand{\tn}{\tabularnewline} % Required as custom column type in use % Font and Colours \definecolor{HeadBackground}{HTML}{333333} \definecolor{FootBackground}{HTML}{666666} \definecolor{TextColor}{HTML}{333333} \definecolor{DarkBackground}{HTML}{0000FF} \definecolor{LightBackground}{HTML}{EFEFFF} \renewcommand{\familydefault}{\sfdefault} \color{TextColor} % Header and Footer \pagestyle{fancy} \fancyhead{} % Set header to blank \fancyfoot{} % Set footer to blank \fancyhead[L]{ \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{C} \SetRowColor{DarkBackground} \vspace{-7pt} {\parbox{\dimexpr\textwidth-2\fboxsep\relax}{\noindent \hspace*{-6pt}\includegraphics[width=5.8cm]{/web/www.cheatography.com/public/images/cheatography_logo.pdf}} } \end{tabulary} \columnbreak \begin{tabulary}{11cm}{L} \vspace{-2pt}\large{\bf{\textcolor{DarkBackground}{\textrm{Entity Framework Cheat Sheet}}}} \\ \normalsize{by \textcolor{DarkBackground}{blinkdata} via \textcolor{DarkBackground}{\uline{cheatography.com/7996/cs/3215/}}} \end{tabulary} \end{multicols}} \fancyfoot[L]{ \footnotesize \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{LL} \SetRowColor{FootBackground} \mymulticolumn{2}{p{5.377cm}}{\bf\textcolor{white}{Cheatographer}} \\ \vspace{-2pt}blinkdata \\ \uline{cheatography.com/blinkdata} \\ \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Cheat Sheet}} \\ \vspace{-2pt}Not Yet Published.\\ Updated 13th May, 2016.\\ Page {\thepage} of \pageref{LastPage}. \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Sponsor}} \\ \SetRowColor{white} \vspace{-5pt} %\includegraphics[width=48px,height=48px]{dave.jpeg} Measure your website readability!\\ www.readability-score.com \end{tabulary} \end{multicols}} \begin{document} \raggedright \raggedcolumns % Set font size to small. Switch to any value % from this page to resize cheat sheet text: % www.emerson.emory.edu/services/latex/latex_169.html \footnotesize % Small font. \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Main Classes (1 per entity)}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{public class Student \newline \{ \newline public Student() \{ \} \newline public int StudentID \{ get; set; \} \newline public string StudentName \{ get; set; \} \newline public DateTime? DateOfBirth \{ get; set; \} \newline public byte{[}{]} Photo \{ get; set; \} \newline public decimal Height \{ get; set; \} \newline public float Weight \{ get; set; \} \newline \newline public int StandardId \{ get; set; \} // foreign key for line below (paired) \newline public Standard Standard \{ get; set; \} // 1 per student \newline \} \newline \newline public class Standard \{ \newline public Standard() \{ \} \newline public int StandardId \{ get; set; \} \newline public string StandardName \{ get; set; \} \newline \newline public ICollection\textless{}Student\textgreater{} Students \{ get; set; \} // many per standard \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{If you dont define the foreign key field name \textless{}class\textgreater{}Id in the Student class, it will be created automatically and called Standard\_StandardId} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{DbContext Class (1 required)}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{public class Context: DbContext \newline \{ \newline // SchoolDbConnectionString is the connection string from the config file \newline public SchoolContext(): \seqsplit{base("name=SchoolDbConnectionString")} \newline \{ \newline //Disable initializer - we dont want to lose data EVER \newline Database.SetInitializer\textless{}SchoolDBContext\textgreater{}(null); \newline \} \newline \newline public DbSet\textless{}Student\textgreater{} Students \{ get; set; \} \newline public DbSet\textless{}Standard\textgreater{} Standards \{ get; set; \} \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Conventions}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{Primary key is Id or \textless{}class name\textgreater{}Id (or use Data Annotation)} \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} \mymulticolumn{1}{x{17.67cm}}{Every Entity MUST have a primary key} \tn % Row Count 3 (+ 1) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{Foreign keys are created as IList\textless{}T\textgreater{} or ICollection\textless{}T\textgreater{}} \tn % Row Count 5 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{x{8.635 cm} x{8.635 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{17.67cm}}{\bf\textcolor{white}{Data Annotations}} \tn % Row 0 \SetRowColor{LightBackground} {[}Key{]} & Make this into a primary key \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} {[}Key{]} {[}Column(Order=1){]} & First part of composite primary key \tn % Row Count 4 (+ 2) % Row 2 \SetRowColor{LightBackground} {[}Key{]} {[}Column(Order=2){]} & Second part of composite primary key \tn % Row Count 6 (+ 2) % Row 3 \SetRowColor{white} {[}TimeStamp{]} public byte{[}{]} RowVersion \{ get; set; \} & Used for concurrency checking. Only works for byte{[}{]}. Autofills \tn % Row Count 10 (+ 4) % Row 4 \SetRowColor{LightBackground} {[}ConcurrencyCheck{]} & Use as a concurrency check. Any type. No autofill \tn % Row Count 13 (+ 3) % Row 5 \SetRowColor{white} {[}Required{]} & Required value. Forces NOT NULL \tn % Row Count 15 (+ 2) % Row 6 \SetRowColor{LightBackground} {[}MaxLength(50){]} & Maximum of 50 characters \tn % Row Count 17 (+ 2) % Row 7 \SetRowColor{white} {[}MinLength(2){]} & Minimum of 2 characters \tn % Row Count 19 (+ 2) % Row 8 \SetRowColor{LightBackground} {[}MaxLength(50),MinLength(2){]} & Min and Max length combined \tn % Row Count 21 (+ 2) % Row 9 \SetRowColor{white} {[}StringLength(50){]} & Make nvarchar(50) instead of nvarchar(max) \tn % Row Count 24 (+ 3) % Row 10 \SetRowColor{LightBackground} {[}Column("Name"){]} & Use this as field name in the DB instead of the property name \tn % Row Count 28 (+ 4) % Row 11 \SetRowColor{white} {[}Column("Name", Typename="varchar"){]} & Set the fieldname and the data type \tn % Row Count 30 (+ 2) \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{x{8.635 cm} x{8.635 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{17.67cm}}{\bf\textcolor{white}{Data Annotations (cont)}} \tn % Row 12 \SetRowColor{LightBackground} {[}NotMapped{]} & Dont create a field in the database (unbound data) \tn % Row Count 3 (+ 3) % Row 13 \SetRowColor{white} {[}ForeignKey("SpecificIdField"){]} & Use the specified id field to hold the foreign key value \tn % Row Count 6 (+ 3) % Row 14 \SetRowColor{LightBackground} {[}Index{]} & Create a non clustered index on thsi field \tn % Row Count 9 (+ 3) % Row 15 \SetRowColor{white} {[}Index( "INDEX\_REGNUM", IsClustered=true, IsUnique=true ){]} & Create a clustered, unique index with the given name (instead of IX\_propertyname) \tn % Row Count 14 (+ 5) % Row 16 \SetRowColor{LightBackground} \mymulticolumn{2}{x{17.67cm}}{} \tn % Row Count 14 (+ 0) % Row 17 \SetRowColor{white} {[}Table("StudentMaster"){]} & Use this as the table name instead of the class name \tn % Row Count 17 (+ 3) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{17.67cm}}{The "Table" annotation goes just before the public class line. All other annotations go before the properties themselves} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{x{8.635 cm} x{8.635 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{17.67cm}}{\bf\textcolor{white}{DbEntityEntry}} \tn % Row 0 \SetRowColor{LightBackground} var entry = \seqsplit{context.Entry(student)} & Get a DbEntityEntry for the current student \tn % Row Count 3 (+ 3) % Row 1 \SetRowColor{white} entry.State & Return Modified, Deleted, Added, Unchanged or Detached \tn % Row Count 6 (+ 3) % Row 2 \SetRowColor{LightBackground} entry.OriginalValues{[}"age"{]} & The original (unchanged) value \tn % Row Count 8 (+ 2) % Row 3 \SetRowColor{white} entry.CurrentValues{[}"age"{]} & The current value \tn % Row Count 10 (+ 2) % Row 4 \SetRowColor{LightBackground} \seqsplit{context.Entry(student).State} = \seqsplit{System.Data.Entity.EntityState.Modified;} & Force to a modified state (even if it hasnt been) Needed for disconnected entities \tn % Row Count 15 (+ 5) % Row 5 \SetRowColor{white} entry.Reload(); & Forces the data to be reloaded from the database (state will become UnChanged) All changes will be lost \tn % Row Count 21 (+ 6) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{17.67cm}}{Note : The context will have been created with: \newline using (var context = new SchoolDBEntities()) \{ \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Add Entity (in disconnected state)}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{// create new Student entity object in disconnected scenario (out of the scope of DbContext) \newline var newStudent = new Student(); \newline \newline //set student name \newline newStudent.StudentName = "Bill"; \newline \newline //create DBContext object \newline using (var dbCtx = new SchoolDBEntities()) \{ \newline //Add Student object into Students DBset \newline \seqsplit{dbCtx.Students.Add(newStudent);} \newline \newline // call SaveChanges method to save student into database \newline dbCtx.SaveChanges(); \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Update Entity (in disconnected state)}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{//1. Get student from DB \newline using (var ctx = new SchoolDBEntities()) \newline \{ \newline stud = ctx.Students.Where(s =\textgreater{} s.StudentName == "New Student1").FirstOrDefault\textless{}Student\textgreater{}(); \newline \} \newline \newline //2. change student name in disconnected mode (out of ctx scope) \newline if (stud != null) \newline \{ \newline stud.StudentName = "Updated Student1"; \newline \} \newline \newline //save modified entity using new Context \newline using (var dbCtx = new SchoolDBEntities()) \newline \{ \newline //3. Mark entity as modified \newline dbCtx.Entry(stud).State = \seqsplit{System.Data.Entity.EntityState.Modified;} \newline \newline //4. call SaveChanges \newline dbCtx.SaveChanges(); \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Delete Entity (in disconnected state)}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{//1. Get student from DB \newline using (var ctx = new SchoolDBEntities()) \newline \{ \newline studentToDelete = ctx.Students.Where(s =\textgreater{} s.StudentName == "Student1").FirstOrDefault\textless{}Student\textgreater{}(); \newline \} \newline \newline //Create new context for disconnected scenario \newline using (var newContext = new SchoolDBEntities()) \newline \{ \newline \seqsplit{newContext.Entry(studentToDelete).State} = \seqsplit{System.Data.Entity.EntityState.Deleted;} \newline \newline \seqsplit{newContext.SaveChanges();} \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Update Entity Graph using DbContext}} \tn \SetRowColor{white} \mymulticolumn{1}{x{17.67cm}}{TBA !!! \newline % Row Count 1 (+ 1) Complex - needs more research at this stage% Row Count 2 (+ 1) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Raw SQL}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{using (var ctx = new SchoolDBEntities()) \newline \{ \newline //Update command \newline int noOfRowUpdated = \seqsplit{ctx.Database.ExecuteSqlCommand("Update} student \newline set studentname ='changed student by command' where studentid=1"); \newline //Insert command \newline int noOfRowInserted = \seqsplit{ctx.Database.ExecuteSqlCommand("insert} into student(studentname) \newline values('New Student')"); \newline //Delete command \newline int noOfRowDeleted = \seqsplit{ctx.Database.ExecuteSqlCommand("delete} from student \newline where studentid=1"); \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Convert DbContext to ObjectContext}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{using (var ctx = new SchoolDBEntities()) \{ \newline var objectContext = (ctx as \seqsplit{System.Data.Entity.Infrastructure.IObjectContextAdapter).ObjectContext;} \newline //use objectContext here.. \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Queries}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{// Get a record by its Primary key value - return null if no record found \newline using (var ctx = new SchoolDBEntities()) \newline \{ \newline var student = ctx.Students.Find(\_id); \newline \} \newline \newline // Get the first (TOP 1) record - return null if no record found \newline using (var ctx = new SchoolDBEntities()) \newline \{ \newline var student = (from s in ctx.Students \newline where s.StudentName == "Student1" \newline select s).FirstOrDefault\textless{}Student\textgreater{}(); \newline \} \newline \newline // Get a List of records that match the criteria \newline using (var ctx = new SchoolDBEntities()) \newline \{ \newline var studentList = (from s in ctx.Students \newline where s.StudentName == "Student1" \newline orderby s.StudentName ascending \newline select s).ToList\textless{}Student\textgreater{}(); \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{17.67cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{17.67cm}}{\bf\textcolor{white}{Other Notes}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{1}{x{17.67cm}}{How to set default values} \tn \mymulticolumn{1}{x{17.67cm}}{\hspace*{6 px}\rule{2px}{6px}\hspace*{6 px}Create a new partial class (don't edit the autogenerated one) and set the default values in the constructor of the new class.} \tn % Row Count 4 (+ 4) \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \end{document}