【问题标题】:.net core 2.0 Entity Framework - Add table relationship at db level and update model.net core 2.0 Entity Framework - 在数据库级别添加表关系并更新模型
【发布时间】:2018-02-01 16:36:18
【问题描述】:

我正在开发一个使用 Entity Framework 实现 .net core 2.0 的应用程序。

我已经通过使用包管理器控制台搭建现有数据库来生成模型。

现在我通过在两个表之间添加缺失关系来手动编辑数据库。

更新模型的最佳方法是什么?

此时我正在删除所有模型文件,并且每次都运行脚手架命令...

如何避免这种情况?

感谢支持

【问题讨论】:

    标签: c# entity-framework .net-core


    【解决方案1】:

    您可以简单地将缺少的虚拟字段添加到对象中。

    如果列有匹配的名称,您可以直接添加它们:

    class Customer {
        public int CustomerId {get;set;} // PK that was already there
    
        // new navigation property
        public virtual ICollection<Account> Accounts { get; set; }
    }
    
    class Account {
        public int AccountId {get;set;} 
    
        // new FK
        public int CustomerId { get;set; }
        // new navigation property
        public virtual Customer Customer {get;set;} 
    }
    

    如果您对同一个表有多个 fks,或者名称不匹配,您可能需要在 DbContext 上的 OnModelCreating 方法中添加一些代码。

    了解这是如何完成的更简单的方法是使用您的工具重新生成一次代码,并将旧代码与 WinMerge 等工具进行比较。 EF Core 比 EF6 简单得多,一旦您理解了这个想法,您将永远不必再次使用这些工具。我亲手编写了所有实体的代码,我发现这比使用这些工具要容易得多。

    【讨论】:

      猜你喜欢
      • 2019-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-10
      • 2014-05-02
      • 1970-01-01
      • 2022-12-10
      • 2021-03-16
      相关资源
      最近更新 更多