簡體   English   中英

何時在 DbContext 構造函數與 OnConfiguring 中提供 DbContextOptions?

[英]when to provide DbContextOptions in DbContext constructor vs OnConfiguring?

提供接受DbContextOptions<MyFileContext>DbContext構造函數與包括連接數據庫的OnConfiguring方法有什么區別?

兩者是等價的嗎?

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.SqlServer;

namespace MyApp.Models
{
    public class MyDbContext : DbContext
    {
        // OPTION 1
        public MyDbContext(DbContextOptions<MyFileContext> options) : base(options)
        {
        }

        public DbSet<MyTable> MyTables { get; set; }

        // OPTION 2
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);

            optionsBuilder.UseSqlServer(AppSettingsProvider.MySqlServerConnection);
        }

    }
}

兩者是等價的嗎?

情況很復雜。 (但理想情況下沒有);

可以通過重寫DbContextOptions方法通過構造函數參數在外部將OnConfiguring提供給DbContext

如果兩者都使用, OnConfiguring最后應用,並且可以覆蓋提供給構造函數參數的選項。

強調我的

參考配置 DbContext

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM