使用Entity Framework CodeFirst模式创建新数据库

开发环境

  • Visual Studio 2010 SP1
  • SQL Server Compact 4.0

演练步骤

  1. 打开Visual Studio;
  2. 新建Console应用程序Known.EFDemo;
  3. 创建Blog模型;
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    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; }
    }
  4. 右击项目->管理NuGet程序包,搜索Entity Framework并安装;或使用程序包管理器控制台运行命令Install-Package EntityFramework
  5. 创建BlogContext;
    1
    2
    3
    4
    public class BlogContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
    }
  6. 修改App.config文件,配置ConnectionString和SQL Server Compact数据提供者工厂;
    1
    2
    3
    4
    5
    6
    7
    8
    9
    <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>
  7. 修改Program并运行,成功后,可以在服务器资源管理器中查看自动生成的表结构及数据。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    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("保存成功!");
    }
  8. 当模型改变时,可以使用命令自动迁移数据库,配置命令:Enable-Migrations –EnableAutomaticMigrations ;更新命令:Update-Database –Verbose 。

 

posted @   known  阅读(4162)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示