![](/img/trans.png)
[英]Entity Framework Core - Migration - No Parameterless Constructor Defined for this Object
[英]Entity Framework Core: No parameterless constructor defined for this dbcontext
當我嘗試使用 Entity Framework Core 生成新的腳手架時遇到問題。 我收到一個錯誤
沒有為此 dbcontext 定義無參數構造函數。
我嘗試了任何解決方案,但沒有任何效果。
這是我的 dbContext:
public class MyDbContext: DbContext
{
public MyDbContext(DbContextOptions<MyDbContext> options)
: base(options)
{
}
public DbSet<Player> Players { get; set; }
public DbSet<PlayerAdvanceStats> PlayerAdvanceStats { get; set; }
public DbSet<Account> Accounts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Player>()
.HasOne(a => a.PlayerAdvanceStats)
.WithOne(a => a.player)
.HasForeignKey<PlayerAdvanceStats>(c => c.PlayerId);
}
}
我在ConfigureService
方法內的Startup
文件中添加了這個:
services.AddDbContext<MyDbContext>
(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
根據文檔https://docs.microsoft.com/en-us/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli
如果 CLI 無法從依賴容器中獲取上下文,它將嘗試查找默認構造函數或設計時工廠。 在您執行其中任何一項之前,您需要問自己為什么它無法在您的容器中找到上下文。
是在不同項目中的上下文,然后是具有主機生成器的項目,那么您需要使用 -s 標志來指定啟動項目。
嘗試將以下內容添加到您的DbContext
class:
public class MyDbContext: DbContext
{
// try adding the parameterless constructor indicated by the error
public MyDbContext() : base() { }
public MyDbContext(DbContextOptions<MyDbContext> options)
: base(options)
{
}
public DbSet<Player> Players { get; set; }
public DbSet<PlayerAdvanceStats> PlayerAdvanceStats { get; set; }
public DbSet<Account> Accounts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Player>()
.HasOne(a => a.PlayerAdvanceStats)
.WithOne(a => a.player)
.HasForeignKey<PlayerAdvanceStats>(c => c.PlayerId);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.