首页 > 代码库 > Entity Framework Code First to a New Database

Entity Framework Code First to a New Database

1. Create the Application

To keep things simple we’re going to build a basic console application that uses Code First to perform data access.

  • Open Visual Studio
  • File -> New -> Project…
  • Select Windows from the left menu and Console Application
  • Enter CodeFirstNewDatabaseSample as the name
  • Select OK

2. Create the Model

技术分享
    public class Department
    {
        [Key]
        public int DepartmentID { get; set; }
        public int CourseID { get; set; }
        [ForeignKey("CourseID")]
        public Course Course { get; set; }
        public string Name { get; set; }
    }
View Code

 

3. Create a Context

  • Project –> Manage NuGet Packages… Note: If you don’t have the Manage NuGet Packages… option you should install the latest version of NuGet
  • Select the Online tab
  • Select the EntityFramework package
  • Click Install
技术分享
    public class QxunDbContext : DbContext 
    {
        public QxunDbContext()
            : base("server=localhost;uid=sa;pwd=6665508a;database=Qxun;")
        { 
        }
        public DbSet<Department> Departments { get; set; } 
    }
View Code

 

4. Reading & Writing Data

技术分享
 using (var db = new BloggingContext()) 
        { 
            // Create and save a new Blog 
            Console.Write("Enter a name for a new Blog: "); 
            var name = Console.ReadLine(); 
 
            var blog = new Blog { Name = name }; 
            db.Blogs.Add(blog); 
            db.SaveChanges(); 
 
            // Display all Blogs from the database 
            var query = from b in db.Blogs 
                        orderby b.Name 
                        select b; 
 
            Console.WriteLine("All blogs in the database:"); 
            foreach (var item in query) 
            { 
                Console.WriteLine(item.Name); 
            } 
 
            Console.WriteLine("Press any key to exit..."); 
            Console.ReadKey(); 
        } 
View Code

 

Entity Framework Code First to a New Database