开发环境
- Visual Studio 2010 SP1
- SQL Server Compact 4.0
演练步骤
- 打开Visual Studio;
- 新建Console应用程序Known.EFDemo;
- 创建Blog模型;
public class Blog { public int Id { get; set; } public string Name { get; set; } public List<Post> Posts { get; set; } } public class Post { public int Id { get; set; } public string Title { get; set; } public string Content { get; set; } }
- 右击项目->管理NuGet程序包,搜索Entity Framework并安装;或使用程序包管理器控制台运行命令Install-Package EntityFramework;
- 创建BlogContext;
public class BlogContext : DbContext { public DbSet<Blog> Blogs { get; set; } }
- 修改App.config文件,配置ConnectionString和SQL Server Compact数据提供者工厂;
<connectionStrings> <add name="BlogContext" connectionString="Data Source=|DataDirectory|Blog.sdf" providerName="System.Data.SqlServerCe.4.0" /> </connectionStrings> <system.data> <DbProviderFactories> <remove invariant="System.Data.SqlServerCe.4.0" /> <add name="Microsoft SQL Server Compact Data Provider 4.0" invariant="System.Data.SqlServerCe.4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" /> </DbProviderFactories> </system.data>
- 修改Program并运行,成功后,可以在服务器资源管理器中查看自动生成的表结构及数据。
using (var context = new BlogContext()) { Console.WriteLine("请输入博客名称:"); var name = Console.ReadLine(); var blog = new Blog { Name = name }; blog.Posts = new List<Post>(); Console.WriteLine("请输入随笔标题:"); var title = Console.ReadLine(); Console.WriteLine("请输入随笔内容:"); var content = Console.ReadLine(); blog.Posts.Add(new Post { Title = title, Content = content }); context.Blogs.Add(blog); context.SaveChanges(); Console.WriteLine("保存成功!"); }
- 当模型改变时,可以使用命令自动迁移数据库,配置命令:Enable-Migrations –EnableAutomaticMigrations ;更新命令:Update-Database –Verbose 。