欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

EF?Core基礎入門教程

 更新時間:2022年04月13日 15:01:34   作者:Ruby_Lu  
這篇文章介紹了EF?Core的基礎入門教程,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下

EF Core 是一個ORM(對象關系映射),它使 .NET 開發(fā)人員可以使用 .NET對象操作數(shù)據(jù)庫,避免了像ADO.NET訪問數(shù)據(jù)庫的代碼,開發(fā)者只需要編寫對象即可。

EF Core 支持多種數(shù)據(jù)庫引擎:

  • Microsoft SQL Sever
  • SQLite
  • Npgsql
  • MySQL
  • ......

1.獲取EF Core

通過NuGet獲取要使用的數(shù)據(jù)庫支持。比如:Microsoft SQL Sever

打開NuGet程序包管理器控制臺,輸入:Install-PackageMicrosoft.EntityFrameworkCore.SqlServer

2.模型

EF Core 是通過一個模型進行數(shù)據(jù)庫訪問的。模型由實體類和表示與數(shù)據(jù)庫中的會話組成的,以及允許你查詢和保存數(shù)據(jù)派生的上下文。

既可以從現(xiàn)有數(shù)據(jù)庫生成模型,也可以使用EF 遷移來完成從模型生成數(shù)據(jù)庫,也就是Database First 和 Code First。

簡單的模型:

    public partial class TestContext : DbContext
    {
        public TestContext()
        {
        }

        public TestContext(DbContextOptions<TestContext> options)
            : base(options)
        {
        }

        public virtual DbSet<User> User { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
                optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=Test;Integrated Security=True");
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {}
    }

使用模型操作數(shù)據(jù)庫:

    public class HomeController : Controller
    {
        private DataContext _context;
        public HomeController(DataContext context)
        {
            _context = context;
        }
        public IActionResult Index()
        {
            _context.User.Add(new User() { Name="name",Password="123"});
            _context.SaveChanges();
            //查詢
            var users = _context.User.ToList();
            return View();
        }

3.Code First

Code First 也就是通過EF遷移來完成從模型生成數(shù)據(jù)庫。

1.創(chuàng)建項目

創(chuàng)建一個ASP.NET Core WEB 應用程序

2.打開NuGet包管理器下載Microsoft.EntityFrameworkCore.SqlServer 和Microsoft.EntityFrameworkCore.Tools

3.在Models文件夾創(chuàng)建實體類和上下文類

public class BlogContext:DbContext
    {
        public BlogContext(DbContextOptions<BlogContext> options)
            : base(options)
        {
        }

        public DbSet<Blog> Blog { get; set; }
        public DbSet<Post> Post { get; set; }
    }
public class Blog
    {
        public int BlogId { get; set; }
        public string Url { get; set; }
        public virtual List<Post> Posts { get; set; }
    }
public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        public int BlogId { get; set; }
        public Blog Blog { get; set; }
    }

4.在ConfigureServices方法中添加上下文依賴注入:

public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            var connectionString = Configuration.GetConnectionString("DefaultConnection");
            services.AddDbContext<BlogContext>(options =>
            options.UseSqlServer(connectionString));

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

5.在appsettings.json中添加鏈接數(shù)據(jù)庫字符串

{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=.;Initial Catalog=Blog;Integrated Security=True"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    }
  },
  "AllowedHosts": "*"
}

6.打開NuGet程序包管理控制臺,先輸入 Add-Migration FirstMigration,再輸入Update-Database。遷移成功后,會創(chuàng)建數(shù)據(jù)庫,以及會在項目中生成一個Migrations文件夾,里面時遷移記錄。

創(chuàng)建成功就可以通過構造函數(shù)依賴注入的方式訪問數(shù)據(jù)庫了。

4.Database First

Database First,也就是通過現(xiàn)有數(shù)據(jù)庫生成模型

1.創(chuàng)建項目,并安裝Microsoft.EntityFrameworkCore.SqlServer , Microsoft.EntityFrameworkCore.Tools 和Microsoft.EntityFrameworkCore.SqlServer.Design

2.在NuGet程序包管理器控制臺輸入:Scaffold-DbContext "Data Source=.;Initial Catalog=Blog;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer 。執(zhí)行成功會生成相關模型:

3,現(xiàn)在可以使用上下文訪問數(shù)據(jù)庫了,但是不能通過依賴注入的方式。如果需要,還是在ConfigureServices方法中添加代碼:services.AddDbContext<BlogContext>()。如果要使用appsettings.json中的連接字符串,就需要按照上面ConfigureServices方法中所寫的。

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

最新評論