EM(Entity FrameWork)- code first , using in Visual stdio 2017

一、创建工程项目

          

二、添加引用

  1.   引用 -> 右键 “ 管理NuGet程序包” -> 在浏览项,搜索 “ EntityFrameWork”,找到 “ EntityFramework ” 和 “ EntityFramework.SqlServerCompact ” 并安装

            

三、代码示例

using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;

namespace test_1
{
    public class Blog
    {
        public int BlogId { get; set; }
        public string Name { get; set; }
    }

    public class DataContext : DbContext
    {
        public DataContext() : base("TelFeeDB")
        {
            // 初始化
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<DataContext, Configuration>());
        }

        public DbSet<Blog> Blogs { get; set; }
    }

    public sealed class Configuration : DbMigrationsConfiguration<DataContext>
    {
        public Configuration()
        {
            // true自动迁移,false手动迁移
            AutomaticMigrationsEnabled = true;
        }
    }

    internal class Test1
    {
        private static void Main(string[] args)
        {
            using (var db = new DataContext())
            {
                var blog = new Blog { Name = "zhang" };
                db.Blogs.Add(blog);
                db.SaveChanges();

                Console.WriteLine("All blogs in the database:");
                foreach (var item in db.Blogs)
                {
                    Console.WriteLine(item.Name);
                }
                Console.ReadKey();
            }
        }
    }
}

  

结果:

 

posted @ 2018-05-07 17:53  Death、MrZ  阅读(180)  评论(0编辑  收藏  举报