码迷,mamicode.com
首页 > 数据库 > 详细

Entity Framework Code First to a New Database

时间:2017-07-08 11:19:42      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:mode   get   adl   pen   string   packages   soft   logs   bsp   

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

标签:mode   get   adl   pen   string   packages   soft   logs   bsp   

原文地址:http://www.cnblogs.com/liandy0906/p/7135933.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!