Entity Framework .Net Core 3.1 - Code First vs Scaffolding

.net-core c# entity-framework-6 entity-framework-core

Question

What I'm trying to do is implementing the model in Code First for this basic entities:

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
}

Questions are:

  1. What is the correct way to implement the relations in Code First ?
  2. Since the database of the application I have to realize will be very big, Can be a good approach designing the database in SqlServer and then proceed to scaffold the tables ?

Thanks to support

1
1
2/3/2020 8:57:32 AM

Accepted Answer

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>();
    }
}

This is basically how to set up your relations in EF code first

Summary

  1. Create Data Model
  2. Create Database Context
  3. Setup EF
  4. Code first Migration

you can find notes on step 3 and 4 here Get Started with Entity Framework 6 Code First

for the second part of your question you can refer to these links to weigh your options

what is advantage of CodeFirst over Database First

EF Code-First Approach Vs Database-First Approach

3 reasons to use code first design

2
2/9/2020 11:56:35 AM

Popular Answer

1) No comment as I never use it.

2) Database-First approach is the most effective to do. Save alot of your time. Yes, design tables in SQL Server, then run Scaffold-DbContext.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow