Tuesday, 3 April 2018

entity framework code first




----------------------------------------------------------

program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var db = new my_context())
            {
             

                var students = db.students.ToList();
                var courses = db.coruses.ToList();
                var teachers = db.teachers.ToList();

                foreach(var s in students)
                {
                    Console.WriteLine("student: " + s.name);
                    Console.Write("courses: ");

                    var courses_taken_by_student = courses.Where(x => x.student_id == s.id);

                    foreach(var c in courses_taken_by_student)
                    {
                        Console.Write(c.name + " ");
                    }

                    Console.WriteLine("");
                    Console.WriteLine("");
                }

                foreach(var t in teachers)
                {
                    Console.WriteLine("teacher: " + t.name);

                    var courses_taught_by_teacher = courses.Where(x => x.teacher_id == t.id);

                    foreach(var c in courses_taught_by_teacher)
                    {
                        Console.WriteLine("courses: "+ c.name);

                        var student_taking_course = students.Where(x => x.id == c.student_id);
                        Console.Write("student: ");

                        foreach(var s in student_taking_course)
                        {
                            Console.Write(s.name + " ");
                        }

                        Console.WriteLine("");
                        Console.WriteLine("");
                    }
                }
            }

            Console.Read();
        }
    }

    public class student
    {
        [Key]
        public int id { get; set; }
        public string name { get; set; }

        public virtual ICollection<course> courses { get; set; }
    }

    public class course
    {
        [Key]
        public int id { get; set; }
        public string name { get; set; }
        public int student_id { get; set; }
        public int teacher_id { get; set; }

        [ForeignKey("student_id")]
        public virtual student Student { get; set; }

        [ForeignKey("teacher_id")]
        public virtual teacher Teacher { get; set; }
    }

    public class teacher
    {
        [Key]
        public int id { get; set; }
        public string name { get; set; }
     
        public virtual ICollection<course> courses { get; set; }
    }

    public class my_context : DbContext
    {
        public my_context() : base("name = mystring") { }

        public virtual DbSet<student> students { get; set; }
        public virtual DbSet<course> coruses { get; set; }
        public virtual DbSet<teacher> teachers { get; set; }
    }
}

------------------------------------------------------------------
//configuration.cs in migration

namespace ConsoleApp2.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<ConsoleApp2.my_context>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
            ContextKey = "ConsoleApp2.my_context";
        }

        protected override void Seed(ConsoleApp2.my_context context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data.

            context.students.AddOrUpdate(new student { name = "wang",id=3 });
            context.students.AddOrUpdate(new student { name = "li",id=5 });
            context.students.AddOrUpdate(new student { name = "zhang",id=10 });
            context.students.AddOrUpdate(new student { name = "zhao", id=15 });

            context.teachers.AddOrUpdate(new teacher { name = "T1",id=3 });
            context.teachers.AddOrUpdate(new teacher { name = "T2",id=8 });

            context.SaveChanges();

            var teacher_1 = context.teachers.SingleOrDefault(x => x.name == "T1").id;
            var teacher_2 = context.teachers.SingleOrDefault(x => x.name == "T2").id;

            var student_1 = context.students.SingleOrDefault(x => x.name == "wang").id;
            var student_2 = context.students.SingleOrDefault(x => x.name == "li").id;
            var student_3 = context.students.SingleOrDefault(x => x.name == "zhang").id;
            var student_4 = context.students.SingleOrDefault(x => x.name == "zhao").id;

            context.coruses.AddOrUpdate(new course { name = "physic", student_id = student_1,teacher_id=teacher_1,id=5 });
            context.coruses.AddOrUpdate(new course { name = "math", student_id = student_1,teacher_id=teacher_1,id=10 });
            context.coruses.AddOrUpdate(new course { name = "math", student_id = student_2,teacher_id=teacher_2,id=13 });
            context.coruses.AddOrUpdate(new course { name = "art", student_id = student_2,teacher_id=teacher_1,id=17 });
            context.coruses.AddOrUpdate(new course { name = "art", student_id = student_3,teacher_id=teacher_2,id=22 });
            context.coruses.AddOrUpdate(new course { name = "art", student_id = student_4,teacher_id=teacher_2,id=26 });
            context.coruses.AddOrUpdate(new course { name = "math", student_id = student_3,teacher_id=teacher_2,id=36 });       

            context.SaveChanges();
        }
    }
}

------------------------------------------------------------------
//first migration.cs
namespace ConsoleApp2.Migrations
{
    using System;
    using System.Data.Entity.Migrations;
    
    public partial class first_migration : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.teachers",
                c => new
                    {
                        id = c.Int(nullable: false, identity: true),
                        name = c.String(),
                    })
                .PrimaryKey(t => t.id);
            
            AddColumn("dbo.courses", "teacher_id", c => c.Int(nullable: false));
            CreateIndex("dbo.courses", "teacher_id");
            AddForeignKey("dbo.courses", "teacher_id", "dbo.teachers", "id", cascadeDelete: true);
        }
        
        public override void Down()
        {
            DropForeignKey("dbo.courses", "teacher_id", "dbo.teachers");
            DropIndex("dbo.courses", new[] { "teacher_id" });
            DropColumn("dbo.courses", "teacher_id");
            DropTable("dbo.teachers");
        }
    }
}
-----------------------------------------------
//app.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>
  <connectionStrings>
    <add name="mystring"
         connectionString= "Server=DESKTOP-2286VQK\SQLEXPRESS;Database=test;Trusted_Connection=True;" providerName = "System.Data.SqlClient"/>
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

------------------------------------------------------------
//console

  student: wang
courses: physic math

student: li
courses: math art

student: zhang
courses: art math

student: zhao
courses: art

teacher: T1
courses: physic
student: wang

courses: math
student: wang

courses: art
student: li

teacher: T2
courses: math
student: li

courses: art
student: zhang

courses: art
student: zhao

courses: math
student: zhang

reference:
https://www.tutorialspoint.com/entity_framework/entity_framework_first_example.htm
https://stackoverflow.com/questions/4867602/entity-framework-there-is-already-an-open-datareader-associated-with-this-comma
https://msdn.microsoft.com/en-us/data/jj591621

No comments:

Post a Comment