gpt4 book ai didi

c# - 为什么调用 modelBuilder.Entity() 会添加配置?

转载 作者:太空宇宙 更新时间:2023-11-03 23:34:52 25 4
gpt4 key购买 nike

我想即时将域类型添加到上下文中。重写 OnModelCreating ,添加类型和配置添加的类型是我假设的非常自然的方式:

public MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<MyEntity>();
modelBuilder.Configurations.Add(new MyEntityConfig())(); // throws exception
}
}

class MyEntityConfig : EntityTypeConfiguration<MyEntity>
{
}

但令人惊讶的是,modelBuilder.Configurations.Add(new MyEntityConfig())()抛出以下异常:

An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code.

Additional information: A configuration for type 'MyEntity' has already been added. To reference the existing configuration use the Entity() or ComplexType() methods.

检查 modelbuilder.Configurations透露调用.Set<T>导致自动添加配置。

有什么解决办法吗?

最佳答案

感谢 sstan 和 DavidL,命令的正确执行顺序是:

base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new MyEntityConfig())();
modelBuilder.Entity<MyEntity>();

关于c# - 为什么调用 modelBuilder.Entity<MyEntity>() 会添加配置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30900225/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com