【问题标题】:Entity Framework .Net Core 3.1 - Code First vs ScaffoldingEntity Framework .Net Core 3.1 - 代码优先与脚手架
【发布时间】:2020-02-03 08:57:32
【问题描述】:

我要做的是在 Code First 中为这个基本实体实现模型:

public class CompanyType{

    public int Id {get;set;}
    public string CompanyType {get;set;}
}

public class Company{

    public int Id {get;set;}
    public string Company {get;set;}
    public string idCompanyType {get;set;} //Related 1-1 to CompanyType 
}

public class Employee{
    public int Id {get;set;}
    public string Company {get;set;}
    public int idCompany {get;set;}  // --> Here I have to relate idCompany with CompanyId ( 1 company , N Employee
}

问题是:

  1. 在 Code First 中实现关系的正确方法是什么?
  2. 由于我要实现的应用程序的数据库会非常大,在SqlServer中设计数据库然后继续搭建表的好方法吗?

感谢支持

【问题讨论】:

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


    【解决方案1】:
    public class CompanyType{
        public int Id {get;set;}
        public string CompanyType {get;set;}
    }
    
    public class Company{
    
        public Company()
        {
            Employees = new HashSet<Employee>();
        }
    
        public int Id {get;set;}
        public string Company {get;set;}
        public int CompanyTypeID
        public virtual CompanyType CompanyType {get;set;}
        public virtual ICollection<Employee> Employees { get; set; }
    }
    
    public class Employee {
    
        public int Id {get;set;}
        public int CompanyID {get;set;}
        public virtual Company Company {get;set;}     
    }
    
    public class SomeContext : DbContext {
        public SomeContext() : base("SomeContext")
        {
        }
        public DbSet<CompanyType> CompanyTypeSet { get; set; }
        public DbSet<Employee> EmployeeSet { get; set; }
        public DbSet<Company> CompanySet { get; set; }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }
    

    这基本上是如何首先在 EF 代码中设置关系

    总结

    1. 创建数据模型
    2. 创建数据库上下文
    3. 设置 EF
    4. 代码优先迁移

    您可以在此处找到第 3 步和第 4 步的说明 Get Started with Entity Framework 6 Code First

    对于您问题的第二部分,您可以参考这些链接来权衡您的选择

    what is advantage of CodeFirst over Database First

    EF Code-First Approach Vs Database-First Approach

    3 reasons to use code first design

    【讨论】:

    • 感谢弗朗西斯科,非常感谢!
    【解决方案2】:

    在我看来,应该取决于一个人,他/她有多舒服。如果你擅长 SQL 方面,请先设计 db,然后再设计脚手架。如果你擅长c#,请使用代码优先的方法

    【讨论】:

    【解决方案3】:

    1) 没有评论,因为我从不使用它。

    2) Database-First 方法是最有效的方法。节省大量时间。是的,在 SQL Server 中设计表,然后运行 ​​Scaffold-DbContext。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-05
      • 2021-05-10
      • 2022-11-17
      相关资源
      最近更新 更多