c# - EF7 DB-First : Scaffold-DBContext produces model without constructor or setter on ICollection

标签 c# entity-framework entity-framework-core

将EntityFramework NuGet包(.Design、.SqlServer和.Tools)升级到7.0并在PM控制台中使用scaffold-dbcontext从数据库重新生成(逆向工程)模型类后,我看到模型中的差异导致了许多项目构建错误。

以下是 scaffold-dbcontext 在 EF6 下生成的(虚拟)模型类示例:

public partial class Foo
{
    public Foo()
    {
        Deps = new HashSet<Dep>();
    }
    public int FooId { get; set; }
    public int BossId { get; set; }
    public virtual Boss Boss { get; set; } = null!;
    public virtual ICollection<Dep> Deps { get; set; }
}

这是我使用 EF7 针对同一数据库得到的结果:

public partial class Foo
{
    public int FooId { get; set; }
    public int BossId { get; set; }
    public virtual Boss Boss { get; set; } = null!;
    public virtual ICollection<Dep> Deps { get; } = new List<Dep>();
}

注意:

  1. EF7 中没有带 HashSet 的构造函数
  2. ICollection 上没有 setter

在我的代码中的许多地方,我正在使用新的依赖集合(全部来自外部数据)构建新实体并将它们添加到上下文中。缺少 setter/constructor 会导致这个问题。

我很难找到有关此(对我来说是破坏性的)更改的任何文档。

  1. 为什么这样做?
  2. 如何解决它带来的限制?
  3. 是否可以选择让 EF7 坚持采用 EF6 方式?

最佳答案

用List替换HashSet是为了在常见场景下获得更好的性能。

删除 setter 和构造函数是常见场景的最简单模式。并介绍T4 templates to customize reverse engineering由于您可以自定义脚手架,因此更改默认值的影响较小。

关于c# - EF7 DB-First : Scaffold-DBContext produces model without constructor or setter on ICollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75270406/

相关文章:

C# Microsoft.Practices.EnterpriseLibrary.Logging 错误

c# - 在 C# 中检测来自 GSM 调制解调器的来电

c# - EF Core 和 DDD : Store ValueObjects in the same table as Entities, 也使用参数化构造函数来设置实体的属性值

c# - 数据库事务中的并发线程导致 .NET Core EF Core 中的重大延迟

c# - RangeAttribute 数据注释未按预期工作

c# - 如何在 C# 中动态调用构造函数?

c# - 使用 EntityFramework 删除单元格值

c# - Entity Framework 与 Oracle 嵌套查询限制

c# - EF Code First 中的多对多关系表示

c# - Entity Framework Core - 首先将动态值分配给代码中的公共(public)列