Skip to content

Instantly share code, notes, and snippets.

@jsheridanwells
Last active May 2, 2018 20:59
Show Gist options
  • Save jsheridanwells/2f2da194af8678ba107e4baac70ed94e to your computer and use it in GitHub Desktop.
Save jsheridanwells/2f2da194af8678ba107e4baac70ed94e to your computer and use it in GitHub Desktop.
More EF Notes

EF Notes Part 1

(Following this tutorial...)

Creating Models

Primary keys can be set as Id or <MODEL NAME>Id.

Foreign keys are set as <MODEL NAME>Id.

public class Enrollment
    {
        public int EnrollmentID { get; set; }
        public int CourseID { get; set; }
        public int StudentID { get; set; }
    }

Nav links are as follows:

One to one: virtual property of model class with property name as model: public virtual <CLASS> <PROP NAME>.

One to many: virtual property of ICollection of model class with property name as model: public virtual ICollection<CLASS> <PROP NAME>

        public virtual Student Student { get; set; }
        public virtual ICollection<Enrollment> Enrollments { get; set; }

Creating a Database Context

A class will look like this:

    public class SchoolContext : DbContext
    {
        public SchoolContext() : base("SchoolContext") { }

        public DbSet<Student> Students { get; set; }
        public DbSet<Enrollment> Enrollments { get; set; }
        public DbSet<Course> Courses { get; set; }



    }

The base of the class gets connection string passed in (this is named in Web Config). (If nothing is passed in, then the string is the name of the class).

Initializing DB with test data

Class can inject System.Data.Entity.DropCreateDatabaseIfModelChanges<SchoolContext>. This re-creates the database if a model changes. Another option re-creates the database every time the app is rebuilt.

context.<TABLE NAME ACCESSOR>.Add(<OBJECT>) adds the the table context.SaveChanges() writes to the database. (If this is done multiple times, it's easier to track source of any errors).

Seed method is called at startup:

protected override void Seed(SchoolContext context) { /.../ }

An example:

    public class SchoolInitializer: System.Data.Entity.DropCreateDatabaseIfModelChanges<SchoolContext>
    {
        protected override void Seed(SchoolContext context)
        {
            var students = new List<Student>
            {
            new Student{FirstMidName="Carson",LastName="Alexander",EnrollmentDate=DateTime.Parse("2005-09-01")},
            new Student{FirstMidName="Meredith",LastName="Alonso",EnrollmentDate=DateTime.Parse("2002-09-01")},
            new Student{FirstMidName="Arturo",LastName="Anand",EnrollmentDate=DateTime.Parse("2003-09-01")},
            new Student{FirstMidName="Gytis",LastName="Barzdukas",EnrollmentDate=DateTime.Parse("2002-09-01")},
            new Student{FirstMidName="Yan",LastName="Li",EnrollmentDate=DateTime.Parse("2002-09-01")},
            new Student{FirstMidName="Peggy",LastName="Justice",EnrollmentDate=DateTime.Parse("2001-09-01")},
            new Student{FirstMidName="Laura",LastName="Norman",EnrollmentDate=DateTime.Parse("2003-09-01")},
            new Student{FirstMidName="Nino",LastName="Olivetto",EnrollmentDate=DateTime.Parse("2005-09-01")}
            };

            var courses = new List<Course>
            {
                new Course { Title = "Art", Credits = 4, CourseID = 1001},
                new Course { Title = "Music", Credits = 3, CourseID = 1002},
                new Course { Title = "Philosophy", Credits = 4, CourseID = 1003},
                new Course { Title = "Poetry", Credits = 4, CourseID = 1004},
                new Course { Title = "Classics", Credits = 5, CourseID = 1005},
            };

            var enrollments = new List<Enrollment>
            {
            new Enrollment{StudentID=1,CourseID=1050,Grade=Grade.A},
            new Enrollment{StudentID=1,CourseID=4022,Grade=Grade.C},
            new Enrollment{StudentID=1,CourseID=4041,Grade=Grade.B},
            new Enrollment{StudentID=2,CourseID=1045,Grade=Grade.B},
            new Enrollment{StudentID=2,CourseID=3141,Grade=Grade.F},
            new Enrollment{StudentID=2,CourseID=2021,Grade=Grade.F},
            new Enrollment{StudentID=3,CourseID=1050},
            new Enrollment{StudentID=4,CourseID=1050,},
            new Enrollment{StudentID=4,CourseID=4022,Grade=Grade.F},
            new Enrollment{StudentID=5,CourseID=4041,Grade=Grade.C},
            new Enrollment{StudentID=6,CourseID=1045},
            new Enrollment{StudentID=7,CourseID=3141,Grade=Grade.A},
            };


            students.ForEach(student => context.Students.Add(student));
            courses.ForEach(course => context.Courses.Add(course));
            enrollments.ForEach(enrollment => context.Enrollments.Add(enrollment));
            context.SaveChanges();


        }
    }

In Web.config, in <entityFramework> tags, add:

    <contexts>
      <context type="EFUniversity.DataAccessLayer.SchoolContext, EFUniversity">
        <databaseInitializer type="EFUniversity.DataAccessLayer.SchoolInitializer, EFUniversity" />
      </context>
    </contexts>

context type = <APP_NAME.DAL_LOCATION.CONTEXT_NAME, ASSEMBLY_NAME>

databaseInitializer type = <APP_NAME.DAL_LOCATION.INITIALIZER_NAME, ASSEMBLY_NAME>

More Settings Here...

It can also be run in Global.asax.cs: Application_Start():

Database.SetInitializer(new SchoolInitializer());

Add connection string to Web.config:

 <connectionStrings>
    <add name="SchoolContext" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=ContosoUniversity1;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
  </connectionStrings>

Data Source is name of sql server

EF Notes Part 2

A Typical CRUD Controller:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment