├── _config.yml ├── src └── ManageEmployees │ ├── appsettings.json │ ├── Models │ ├── IEntityBase.cs │ ├── Enums │ │ ├── RecordStatus.cs │ │ └── JobPosition.cs │ └── Entities │ │ ├── Department.cs │ │ ├── Contract.cs │ │ └── Employee.cs │ ├── Data │ ├── Abstract │ │ ├── IRepositories.cs │ │ └── IEntityBaseRepository.cs │ ├── Repositories │ │ ├── ContractRepository.cs │ │ ├── EmployeeRepository.cs │ │ └── DepartmentRepository.cs │ ├── ManageEmployeesContext.cs │ ├── Base │ │ └── EntityBaseRepository.cs │ └── ManageEmployeesDbInitializer.cs │ ├── Program.cs │ ├── web.config │ ├── Properties │ └── launchSettings.json │ ├── ManageEmployees.csproj │ ├── Startup.cs │ ├── Controllers │ ├── DepartmentController.cs │ ├── ContractController.cs │ └── EmployeeController.cs │ ├── Migrations │ ├── 20170330111522_Test.Designer.cs │ ├── ManageEmployeesContextModelSnapshot.cs │ └── 20170330111522_Test.cs │ └── Project_Readme.html ├── README.md ├── ManageEmployees.sln ├── .gitattributes └── .gitignore /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /src/ManageEmployees/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "IncludeScopes": false, 4 | "LogLevel": { 5 | "Default": "Debug", 6 | "System": "Information", 7 | "Microsoft": "Information" 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/ManageEmployees/Models/IEntityBase.cs: -------------------------------------------------------------------------------- 1 | using ManageEmployees.Models.Enums; 2 | 3 | namespace ManageEmployees.Models 4 | { 5 | public interface IEntityBase 6 | { 7 | int Id { get; set; } 8 | RecordStatus RecordStatus { get; set; } 9 | } 10 | } -------------------------------------------------------------------------------- /src/ManageEmployees/Data/Abstract/IRepositories.cs: -------------------------------------------------------------------------------- 1 | using ManageEmployees.Models.Entities; 2 | 3 | namespace ManageEmployees.Data.Abstract 4 | { 5 | public interface IEmployeeRepository : IEntityBaseRepository { } 6 | 7 | public interface IContractRepository : IEntityBaseRepository { } 8 | 9 | public interface IDepartmentRepository : IEntityBaseRepository { } 10 | } 11 | -------------------------------------------------------------------------------- /src/ManageEmployees/Models/Enums/RecordStatus.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using Newtonsoft.Json.Converters; 3 | using System.Runtime.Serialization; 4 | 5 | namespace ManageEmployees.Models.Enums 6 | { 7 | 8 | [JsonConverter(typeof(StringEnumConverter))] 9 | public enum RecordStatus 10 | { 11 | Active, 12 | Deleted, 13 | Archived, 14 | Pending 15 | } 16 | } -------------------------------------------------------------------------------- /src/ManageEmployees/Models/Enums/JobPosition.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using Newtonsoft.Json.Converters; 3 | using System.Runtime.Serialization; 4 | 5 | namespace ManageEmployees.Models.Enums 6 | { 7 | 8 | [JsonConverter(typeof(StringEnumConverter))] 9 | public enum JobPosition 10 | { 11 | Trainee, 12 | Junior, 13 | Senior, 14 | Expert, 15 | Manager 16 | } 17 | } -------------------------------------------------------------------------------- /src/ManageEmployees/Data/Repositories/ContractRepository.cs: -------------------------------------------------------------------------------- 1 | using ManageEmployees.Data.Abstract; 2 | using ManageEmployees.Data.Base; 3 | using ManageEmployees.Models.Entities; 4 | 5 | namespace ManageEmployees.Data.Repositories 6 | { 7 | public class ContractRepository : EntityBaseRepository, IContractRepository 8 | { 9 | public ContractRepository(ManageEmployeesContext context) : base(context) { } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/ManageEmployees/Data/Repositories/EmployeeRepository.cs: -------------------------------------------------------------------------------- 1 | using ManageEmployees.Data.Abstract; 2 | using ManageEmployees.Data.Base; 3 | using ManageEmployees.Models.Entities; 4 | 5 | namespace ManageEmployees.Data.Repositories 6 | { 7 | public class EmployeeRepository : EntityBaseRepository, IEmployeeRepository 8 | { 9 | public EmployeeRepository(ManageEmployeesContext context) : base(context) { } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/ManageEmployees/Data/Repositories/DepartmentRepository.cs: -------------------------------------------------------------------------------- 1 | using ManageEmployees.Data.Abstract; 2 | using ManageEmployees.Data.Base; 3 | using ManageEmployees.Models.Entities; 4 | 5 | namespace ManageEmployees.Data.Repositories 6 | { 7 | public class DepartmentRepository : EntityBaseRepository, IDepartmentRepository 8 | { 9 | public DepartmentRepository(ManageEmployeesContext context) : base(context) { } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/ManageEmployees/Program.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using Microsoft.AspNetCore.Hosting; 3 | 4 | namespace ManageEmployees 5 | { 6 | public class Program 7 | { 8 | public static void Main(string[] args) 9 | { 10 | var host = new WebHostBuilder() 11 | .UseKestrel() 12 | .UseContentRoot(Directory.GetCurrentDirectory()) 13 | .UseIISIntegration() 14 | .UseStartup() 15 | .Build(); 16 | 17 | host.Run(); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/ManageEmployees/web.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/ManageEmployees/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:13743/", 7 | "sslPort": 0 8 | } 9 | }, 10 | "profiles": { 11 | "IIS Express": { 12 | "commandName": "IISExpress", 13 | "launchBrowser": true, 14 | "launchUrl": "api/employee", 15 | "environmentVariables": { 16 | "ASPNETCORE_ENVIRONMENT": "Development" 17 | } 18 | }, 19 | "ManageEmployees": { 20 | "commandName": "Project", 21 | "launchBrowser": true, 22 | "launchUrl": "http://localhost:5000/api/employee", 23 | "environmentVariables": { 24 | "ASPNETCORE_ENVIRONMENT": "Development" 25 | } 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /src/ManageEmployees/Models/Entities/Department.cs: -------------------------------------------------------------------------------- 1 | using ManageEmployees.Models.Enums; 2 | using Newtonsoft.Json; 3 | using System.Collections.Generic; 4 | using System.ComponentModel.DataAnnotations; 5 | using System.ComponentModel.DataAnnotations.Schema; 6 | 7 | namespace ManageEmployees.Models.Entities 8 | { 9 | public class Department : IEntityBase 10 | { 11 | public Department() 12 | { 13 | Employees = new List(); 14 | } 15 | 16 | [Key,Column(Order = 0)] 17 | public int Id { get; set; } 18 | 19 | [Required(ErrorMessage = "Department name is required.")] 20 | [StringLength(120)] 21 | [JsonProperty("name")] 22 | public string Name { get; set; } 23 | 24 | 25 | [Required(ErrorMessage = "Department description is required.")] 26 | [JsonProperty("description")] 27 | public string Description { get; set; } 28 | public RecordStatus RecordStatus { get; set; } 29 | 30 | public ICollection Employees { get; set; } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/ManageEmployees/Data/Abstract/IEntityBaseRepository.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Linq.Expressions; 4 | using ManageEmployees.Models; 5 | 6 | namespace ManageEmployees.Data.Abstract 7 | { 8 | public interface IEntityBaseRepository where T : class, IEntityBase, new() 9 | { 10 | IQueryable AllIncluding(params Expression>[] includeProperties); 11 | IQueryable GetAll(); 12 | int Count(); 13 | T GetSingle(int id); 14 | T GetSingle(Expression> predicate); 15 | T GetSingle(Expression> predicate, params Expression>[] includeProperties); 16 | IQueryable FindBy(Expression> predicate); 17 | void Add(T entity); 18 | void Update(T entity); 19 | void Delete(T entity); 20 | void SetStatusDeleted(T entity); 21 | void SetStatusActive(T entity); 22 | void SetStatusArchived(T entity); 23 | void SetStatusPending(T entity); 24 | void DeleteWhere(Expression> predicate); 25 | void Commit(); 26 | } 27 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | **REST API using ASP.NET Core, Entity Framework Core and Code First Pattern**## 2 | 3 | 4 | ### Technologies used: 5 | • ASP.NET Core 6 | • Entity Framework Core 7 | • Entity Framework Migrations – Code First 8 | • Repository pattern 9 | 10 | ### **1. Installing .NET Core** 11 | To install .NET Core please follow the steps on the official web site https://www.microsoft.com/net/core#windowsvs2015 12 | 13 | ### **2. Opening project** 14 | -Open the solution in VS 2017 15 | 16 | -Open Package Manager Console on the project by going to: Tools > Nuget Package Manager > Package Manager Console 17 | 18 | -On the start up class modify the database connection string (connection) to reflect your database environment 19 | 20 | -Run the following commands (they will create the database schema on your database environment): 21 | 22 | dotnet ef migrations add MyMigration 23 | 24 | dotnet ef database update 25 | 26 | 27 | 28 | ### **3. Build and Run** 29 | You could test the API using POSTMAN which can be downloaded from here: https://www.getpostman.com/ 30 | 31 | ### **4. How to set up the project** 32 | - https://www.youtube.com/watch?v=AYgs0kLjTLE&t=11s 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /src/ManageEmployees/Models/Entities/Contract.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel.DataAnnotations; 3 | using System.ComponentModel.DataAnnotations.Schema; 4 | using ManageEmployees.Models.Enums; 5 | using Microsoft.AspNetCore.Mvc; 6 | 7 | namespace ManageEmployees.Models.Entities 8 | { 9 | public class Contract : IEntityBase 10 | { 11 | [Key, Column(Order = 0)] 12 | 13 | public int Id { get; set; } 14 | 15 | [Required(ErrorMessage = "Contract name is required.")] 16 | [StringLength(120)] 17 | public string Name { get; set; } 18 | 19 | [DataType(DataType.Date)] 20 | [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] 21 | public DateTime StartDate { get; set; } 22 | 23 | [DataType(DataType.Date)] 24 | [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] 25 | public DateTime EndDate { get; set; } 26 | 27 | [Required] 28 | public int Amount { get; set; } 29 | 30 | 31 | [ForeignKey("Employee")] 32 | public int EmployeeId { get; set; } 33 | 34 | 35 | public Employee Employee { get; set; } 36 | 37 | public RecordStatus RecordStatus { get; set; } 38 | 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /ManageEmployees.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26228.10 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{45AB64A3-3C42-4B0A-B3C1-386E118A8DCE}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{728100C9-71B9-48CD-9FC4-D03023AD2872}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ManageEmployees", "src\ManageEmployees\ManageEmployees.csproj", "{54618CEA-9517-4A41-B3EA-1B05BBEBDE36}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {54618CEA-9517-4A41-B3EA-1B05BBEBDE36}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {54618CEA-9517-4A41-B3EA-1B05BBEBDE36}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {54618CEA-9517-4A41-B3EA-1B05BBEBDE36}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {54618CEA-9517-4A41-B3EA-1B05BBEBDE36}.Release|Any CPU.Build.0 = Release|Any CPU 22 | EndGlobalSection 23 | GlobalSection(SolutionProperties) = preSolution 24 | HideSolutionNode = FALSE 25 | EndGlobalSection 26 | GlobalSection(NestedProjects) = preSolution 27 | {54618CEA-9517-4A41-B3EA-1B05BBEBDE36} = {45AB64A3-3C42-4B0A-B3C1-386E118A8DCE} 28 | EndGlobalSection 29 | EndGlobal 30 | -------------------------------------------------------------------------------- /src/ManageEmployees/Models/Entities/Employee.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.ComponentModel.DataAnnotations.Schema; 5 | using ManageEmployees.Models.Enums; 6 | using Newtonsoft.Json; 7 | 8 | namespace ManageEmployees.Models.Entities 9 | { 10 | public class Employee : IEntityBase 11 | { 12 | public Employee() 13 | { 14 | Contracts = new List(); 15 | } 16 | 17 | [Key, Column(Order = 0)] 18 | public int Id { get; set; } 19 | 20 | [Required(ErrorMessage = "Last Name is required")] 21 | [StringLength(120)] 22 | [JsonProperty("lastName")] 23 | public string LastName { get; set; } 24 | 25 | [Required(ErrorMessage = "Last Name is required")] 26 | [StringLength(120)] 27 | [JsonProperty("firstName")] 28 | public string FirstName { get; set; } 29 | 30 | [DataType(DataType.Date)] 31 | [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] 32 | [JsonProperty("birthDate")] 33 | public DateTime BirthDate { get; set; } 34 | 35 | [Required] 36 | [JsonProperty("jobPosition")] 37 | public JobPosition JobPosition { get; set; } 38 | 39 | public RecordStatus RecordStatus { get; set; } 40 | 41 | [ForeignKey("Department")] 42 | [JsonProperty("departmentId")] 43 | public int DepartmentId { get; set; } 44 | 45 | public Department Department { get; set; } 46 | public ICollection Contracts { get; set; } 47 | } 48 | 49 | public class EmployeeViewModel 50 | { 51 | [JsonProperty("lastName")] 52 | public string LastName { get; set; } 53 | [JsonProperty("firstName")] 54 | public string FirstName { get; set; } 55 | [JsonProperty("birthDate")] 56 | public DateTime BirthDate { get; set; } 57 | [JsonProperty("jobPosition")] 58 | public JobPosition JobPosition { get; set; } 59 | [JsonProperty("departmentId")] 60 | public int DepartmentId { get; set; } 61 | 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/ManageEmployees/ManageEmployees.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp1.1 5 | portable 6 | true 7 | ManageEmployees 8 | Exe 9 | ManageEmployees 10 | 1.1.1 11 | $(PackageTargetFallback);dotnet5.6;portable-net45+win8 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /src/ManageEmployees/Data/ManageEmployeesContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using ManageEmployees.Models.Entities; 4 | using ManageEmployees.Models.Enums; 5 | using Microsoft.EntityFrameworkCore; 6 | using Microsoft.EntityFrameworkCore.Metadata; 7 | 8 | namespace ManageEmployees.Data 9 | { 10 | public class ManageEmployeesContext : DbContext 11 | { 12 | public DbSet Employees { get; set; } 13 | public DbSet Departments { get; set; } 14 | public DbSet Contracts { get; set; } 15 | 16 | public ManageEmployeesContext(DbContextOptions options) : base(options) 17 | { 18 | 19 | } 20 | 21 | protected override void OnModelCreating(ModelBuilder modelBuilder) 22 | { 23 | base.OnModelCreating(modelBuilder); 24 | 25 | foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys())) 26 | { 27 | relationship.DeleteBehavior = DeleteBehavior.Restrict; 28 | } 29 | 30 | modelBuilder.Entity().ToTable("Employee"); 31 | modelBuilder.Entity().Property(s => s.DepartmentId).IsRequired(); 32 | modelBuilder.Entity().Property(s => s.BirthDate).HasDefaultValue(DateTime.Now); 33 | modelBuilder.Entity().Property(s => s.FirstName); 34 | modelBuilder.Entity().Property(s => s.LastName).IsRequired(); 35 | modelBuilder.Entity().Property(s => s.JobPosition).HasDefaultValue(JobPosition.Junior); 36 | modelBuilder.Entity().HasOne(s => s.Department).WithMany(s => s.Employees).HasForeignKey(d=>d.DepartmentId); 37 | 38 | modelBuilder.Entity().ToTable("Department"); 39 | modelBuilder.Entity().Property(s => s.Name).IsRequired().HasMaxLength(200); 40 | modelBuilder.Entity().Property(s => s.Description).IsRequired(); 41 | modelBuilder.Entity().HasMany(s => s.Employees); 42 | 43 | modelBuilder.Entity().ToTable("Contract"); 44 | modelBuilder.Entity().Property(s => s.Amount); 45 | modelBuilder.Entity().Property(s => s.EmployeeId).IsRequired(); 46 | modelBuilder.Entity().Property(s => s.StartDate).HasDefaultValue(DateTime.Now).IsRequired(); 47 | modelBuilder.Entity().Property(s => s.EndDate).HasDefaultValue(DateTime.Now).IsRequired(); 48 | modelBuilder.Entity().HasOne(s => s.Employee); 49 | 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /src/ManageEmployees/Startup.cs: -------------------------------------------------------------------------------- 1 | using ManageEmployees.Data; 2 | using ManageEmployees.Data.Abstract; 3 | using ManageEmployees.Data.Repositories; 4 | using Microsoft.AspNetCore.Builder; 5 | using Microsoft.AspNetCore.Hosting; 6 | using Microsoft.EntityFrameworkCore; 7 | using Microsoft.Extensions.Configuration; 8 | using Microsoft.Extensions.DependencyInjection; 9 | using Microsoft.Extensions.Logging; 10 | using Newtonsoft.Json; 11 | 12 | namespace ManageEmployees 13 | { 14 | public class Startup 15 | { 16 | public Startup(IHostingEnvironment env) 17 | { 18 | var builder = new ConfigurationBuilder() 19 | .SetBasePath(env.ContentRootPath) 20 | .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) 21 | .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) 22 | .AddEnvironmentVariables(); 23 | Configuration = builder.Build(); 24 | } 25 | 26 | public IConfigurationRoot Configuration { get; } 27 | 28 | // This method gets called by the runtime. Use this method to add services to the container. 29 | public void ConfigureServices(IServiceCollection services) 30 | { 31 | var connection = @"Server=(localdb)\mssqllocaldb;Database=ManageEmployees;Trusted_Connection=True;"; 32 | services.AddDbContext(options => options.UseSqlServer(connection)); 33 | 34 | // Repositories 35 | services.AddScoped(); 36 | services.AddScoped(); 37 | services.AddScoped(); 38 | 39 | //Adding Cors Config 40 | services.AddCors(options => 41 | { 42 | options.AddPolicy("AllowAll", 43 | p => p.AllowAnyOrigin(). 44 | AllowAnyMethod(). 45 | AllowAnyHeader(). 46 | AllowCredentials()); 47 | }); 48 | 49 | // Add framework services. 50 | services.AddMvc() 51 | .AddJsonOptions(options => 52 | { 53 | options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; 54 | options.SerializerSettings.Formatting = Formatting.Indented; 55 | }); 56 | 57 | 58 | } 59 | 60 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 61 | public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 62 | { 63 | loggerFactory.AddConsole(Configuration.GetSection("Logging")); 64 | loggerFactory.AddDebug(); 65 | 66 | app.UseMvc(); 67 | app.UseCors("AllowAll"); 68 | 69 | ManageEmployeesDbInitializer.Initialize(app.ApplicationServices); 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/ManageEmployees/Data/Base/EntityBaseRepository.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Linq.Expressions; 4 | using ManageEmployees.Data.Abstract; 5 | using ManageEmployees.Models; 6 | using Microsoft.EntityFrameworkCore; 7 | using Microsoft.EntityFrameworkCore.ChangeTracking; 8 | using ManageEmployees.Models.Enums; 9 | 10 | namespace ManageEmployees.Data.Base 11 | { 12 | public class EntityBaseRepository : IEntityBaseRepository where T : class, IEntityBase, new() 13 | { 14 | private readonly ManageEmployeesContext _context; 15 | 16 | public EntityBaseRepository(ManageEmployeesContext context) 17 | { 18 | _context = context; 19 | } 20 | 21 | public virtual IQueryable GetAll() 22 | { 23 | return _context.Set().AsQueryable(); 24 | } 25 | 26 | public virtual int Count() 27 | { 28 | return _context.Set().Count(); 29 | } 30 | 31 | public virtual IQueryable AllIncluding(params Expression>[] includeProperties) 32 | { 33 | IQueryable query = _context.Set(); 34 | query = includeProperties.Aggregate(query, (current, includeProperty) => current.Include(includeProperty)); 35 | return query.AsQueryable(); 36 | } 37 | 38 | public T GetSingle(int id) 39 | { 40 | return _context.Set().FirstOrDefault(x => x.Id == id); 41 | } 42 | 43 | public T GetSingle(Expression> predicate) 44 | { 45 | return _context.Set().FirstOrDefault(predicate); 46 | } 47 | 48 | public T GetSingle(Expression> predicate, params Expression>[] includeProperties) 49 | { 50 | IQueryable query = _context.Set(); 51 | query = includeProperties.Aggregate(query, (current, includeProperty) => current.Include(includeProperty)); 52 | 53 | return query.Where(predicate).FirstOrDefault(); 54 | } 55 | 56 | public virtual IQueryable FindBy(Expression> predicate) 57 | { 58 | return _context.Set().Where(predicate); 59 | } 60 | 61 | public virtual void Add(T entity) 62 | { 63 | _context.Set().Add(entity); 64 | } 65 | 66 | public virtual void Update(T entity) 67 | { 68 | EntityEntry dbEntityEntry = _context.Entry(entity); 69 | dbEntityEntry.State = EntityState.Modified; 70 | } 71 | 72 | public virtual void Delete(T entity) 73 | { 74 | EntityEntry dbEntityEntry = _context.Entry(entity); 75 | dbEntityEntry.State = EntityState.Deleted; 76 | } 77 | 78 | public virtual void SetStatusDeleted(T entity) 79 | { 80 | entity.RecordStatus = RecordStatus.Deleted; 81 | } 82 | public virtual void SetStatusActive(T entity) 83 | { 84 | entity.RecordStatus = RecordStatus.Active; 85 | } 86 | public virtual void SetStatusArchived(T entity) 87 | { 88 | entity.RecordStatus = RecordStatus.Archived; 89 | } 90 | public virtual void SetStatusPending(T entity) 91 | { 92 | entity.RecordStatus = RecordStatus.Pending; 93 | } 94 | 95 | public virtual void DeleteWhere(Expression> predicate) 96 | { 97 | var entities = _context.Set().Where(predicate); 98 | 99 | foreach (var entity in entities) 100 | { 101 | _context.Entry(entity).State = EntityState.Deleted; 102 | } 103 | } 104 | 105 | public virtual void Commit() 106 | { 107 | _context.SaveChanges(); 108 | } 109 | } 110 | 111 | } 112 | -------------------------------------------------------------------------------- /src/ManageEmployees/Controllers/DepartmentController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using ManageEmployees.Data.Abstract; 4 | using ManageEmployees.Models.Entities; 5 | using Microsoft.AspNetCore.Mvc; 6 | using Microsoft.AspNetCore.Cors; 7 | using ManageEmployees.Models.Enums; 8 | 9 | namespace ManageEmployees.Controllers 10 | { 11 | [Route("api/[controller]")] 12 | [EnableCors("AllowAll")] 13 | public class DepartmentController : Controller 14 | { 15 | private readonly IDepartmentRepository _departmentRepository; 16 | private readonly IEmployeeRepository _employeeRepository; 17 | 18 | public DepartmentController(IDepartmentRepository departmentRepository, IEmployeeRepository employeeRepository) 19 | { 20 | this._departmentRepository = departmentRepository; 21 | this._employeeRepository = employeeRepository; 22 | } 23 | 24 | 25 | [HttpGet] 26 | public IActionResult Get() 27 | { 28 | var departments = _departmentRepository.AllIncluding(emp=>emp.Employees).Where(rs => rs.RecordStatus == RecordStatus.Active); 29 | 30 | if (departments.Any()) 31 | return Ok(departments); 32 | return NoContent(); 33 | } 34 | 35 | 36 | [HttpGet("{id}")] 37 | public IActionResult Get(int id) 38 | { 39 | Department department = _departmentRepository.GetSingle(p => p.Id == id, e => e.Employees); 40 | 41 | if (department != null) 42 | return Ok(department); 43 | return NotFound(); 44 | } 45 | 46 | [HttpGet("{id}/employees")] 47 | public IActionResult GetDepartmentEmployees(int id) 48 | { 49 | var departmentEmployees = _employeeRepository.AllIncluding(c=>c.Contracts).Where(dep => dep.DepartmentId == id); 50 | 51 | if (departmentEmployees != null) 52 | return Ok(departmentEmployees); 53 | return NotFound(); 54 | } 55 | 56 | [HttpPost] 57 | public IActionResult Post([FromBody] Department department) 58 | { 59 | try 60 | { 61 | var _department = department; 62 | if (_department == null) throw new ArgumentNullException(nameof(_department)); 63 | _departmentRepository.Add(_department); 64 | _departmentRepository.Commit(); 65 | 66 | return Created($"/api/department/{department.Id}", _department); 67 | } 68 | catch (Exception ex) 69 | { 70 | return BadRequest(ex.Message); 71 | } 72 | } 73 | 74 | [HttpPut("{id}")] 75 | public void Put(int id, [FromBody] Department department) 76 | { 77 | try 78 | { 79 | var _department = _departmentRepository.GetSingle(id); 80 | if (_department == null) throw new ArgumentNullException(nameof(_department)); 81 | _department.Name = department.Name; 82 | _department.RecordStatus = department.RecordStatus; 83 | _department.Description = department.Description; 84 | _departmentRepository.Commit(); 85 | } 86 | catch (Exception ex) 87 | { 88 | throw new Exception(ex.Message); 89 | } 90 | } 91 | 92 | [HttpDelete("{id}")] 93 | public IActionResult Delete(int id) 94 | { 95 | var department = _departmentRepository.GetSingle(id); 96 | if (department == null) throw new ArgumentNullException(nameof(department)); 97 | 98 | var departmentEmployees = _employeeRepository.FindBy(a => a.DepartmentId == id); 99 | 100 | if (departmentEmployees.Any()) return BadRequest("Department you want to delete has employees assigned."); 101 | 102 | _departmentRepository.SetStatusDeleted(department); 103 | _departmentRepository.Commit(); 104 | 105 | return new NoContentResult(); 106 | } 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/ManageEmployees/Controllers/ContractController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using ManageEmployees.Data.Abstract; 3 | using ManageEmployees.Models.Entities; 4 | using Microsoft.AspNetCore.Mvc; 5 | using Microsoft.AspNetCore.Cors; 6 | using ManageEmployees.Models.Enums; 7 | using System.Linq; 8 | 9 | namespace ManageEmployees.Controllers 10 | { 11 | [Route("api/[controller]")] 12 | [EnableCors("AllowAll")] 13 | public class ContractController : Controller 14 | { 15 | private readonly IContractRepository _contractRepository; 16 | private readonly IEmployeeRepository _employeeRepository; 17 | 18 | public ContractController(IContractRepository contractRepository, IEmployeeRepository employeeRepository) 19 | { 20 | this._contractRepository = contractRepository; 21 | this._employeeRepository = employeeRepository; 22 | } 23 | 24 | [HttpGet] 25 | public IActionResult Get() 26 | { 27 | var contracts = _contractRepository.AllIncluding(e=>e.Employee).Where(rs => rs.RecordStatus == RecordStatus.Active); 28 | 29 | if (contracts.Any()) 30 | return Ok(contracts); 31 | return NoContent(); 32 | } 33 | 34 | [HttpGet("{id}")] 35 | public IActionResult Get(int id) 36 | { 37 | Contract contract = _contractRepository.GetSingle(p=>p.Id==id, p=>p.Employee); 38 | if (contract != null) return Ok(contract); 39 | return NotFound(); 40 | } 41 | 42 | [HttpPost] 43 | public IActionResult Post([FromBody] dynamic contract) 44 | { 45 | try 46 | { 47 | var _contract = new Contract() 48 | { 49 | Name = contract.Name, 50 | StartDate = contract.startDate, 51 | EndDate = contract.endDate, 52 | Amount = contract.amount, 53 | EmployeeId = contract.employeeId 54 | }; 55 | 56 | if (_contract == null) throw new ArgumentNullException(nameof(_contract)); 57 | if(_employeeRepository.GetSingle(_contract.EmployeeId) == null) throw new ArgumentNullException($"Department you want to delete has employees assigned."); 58 | 59 | _contractRepository.Add(_contract); 60 | _contractRepository.Commit(); 61 | 62 | return Created($"/api/contract/", _contract); 63 | } 64 | catch (Exception ex) 65 | { 66 | return BadRequest(ex.Message); 67 | } 68 | } 69 | 70 | 71 | [HttpPut("{id}")] 72 | public void Put(int id, [FromBody] Contract contract) 73 | { 74 | try 75 | { 76 | var _contract = _contractRepository.GetSingle(id); 77 | 78 | if (_contract == null) throw new ArgumentNullException(nameof(_contract)); 79 | _contract.Name = contract.Name; 80 | _contract.Amount = contract.Amount; 81 | _contract.EndDate = contract.EndDate; 82 | _contract.StartDate = contract.StartDate; 83 | _contract.RecordStatus = contract.RecordStatus; 84 | 85 | if (_employeeRepository.GetSingle(contract.EmployeeId) == null) throw new ArgumentNullException($"Department you want to delete has employees assigned."); 86 | _contract.EmployeeId = contract.EmployeeId; 87 | _contractRepository.Commit(); 88 | } 89 | catch (Exception ex) 90 | { 91 | throw new Exception(ex.Message); 92 | } 93 | } 94 | 95 | 96 | [HttpDelete("{id}")] 97 | public IActionResult Delete(int id) 98 | { 99 | var contract = _contractRepository.GetSingle(id); 100 | 101 | if (contract == null) return new NotFoundResult(); 102 | 103 | _contractRepository.SetStatusDeleted(contract); 104 | _contractRepository.Commit(); 105 | return new NoContentResult(); 106 | } 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/ManageEmployees/Migrations/20170330111522_Test.Designer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Infrastructure; 4 | using Microsoft.EntityFrameworkCore.Metadata; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using ManageEmployees.Data; 7 | using ManageEmployees.Models.Enums; 8 | 9 | namespace ManageEmployees.Migrations 10 | { 11 | [DbContext(typeof(ManageEmployeesContext))] 12 | [Migration("20170330111522_Test")] 13 | partial class Test 14 | { 15 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 16 | { 17 | modelBuilder 18 | .HasAnnotation("ProductVersion", "1.1.1") 19 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 20 | 21 | modelBuilder.Entity("ManageEmployees.Models.Entities.Contract", b => 22 | { 23 | b.Property("Id") 24 | .ValueGeneratedOnAdd(); 25 | 26 | b.Property("Amount"); 27 | 28 | b.Property("EmployeeId"); 29 | 30 | b.Property("EndDate") 31 | .ValueGeneratedOnAdd() 32 | .HasDefaultValue(new DateTime(2017, 3, 30, 11, 15, 22, 72, DateTimeKind.Local)); 33 | 34 | b.Property("Name") 35 | .IsRequired() 36 | .HasMaxLength(120); 37 | 38 | b.Property("RecordStatus"); 39 | 40 | b.Property("StartDate") 41 | .ValueGeneratedOnAdd() 42 | .HasDefaultValue(new DateTime(2017, 3, 30, 11, 15, 22, 71, DateTimeKind.Local)); 43 | 44 | b.HasKey("Id"); 45 | 46 | b.HasIndex("EmployeeId"); 47 | 48 | b.ToTable("Contract"); 49 | }); 50 | 51 | modelBuilder.Entity("ManageEmployees.Models.Entities.Department", b => 52 | { 53 | b.Property("Id") 54 | .ValueGeneratedOnAdd(); 55 | 56 | b.Property("Description") 57 | .IsRequired(); 58 | 59 | b.Property("Name") 60 | .IsRequired() 61 | .HasMaxLength(200); 62 | 63 | b.Property("RecordStatus"); 64 | 65 | b.HasKey("Id"); 66 | 67 | b.ToTable("Department"); 68 | }); 69 | 70 | modelBuilder.Entity("ManageEmployees.Models.Entities.Employee", b => 71 | { 72 | b.Property("Id") 73 | .ValueGeneratedOnAdd(); 74 | 75 | b.Property("BirthDate") 76 | .ValueGeneratedOnAdd() 77 | .HasDefaultValue(new DateTime(2017, 3, 30, 11, 15, 22, 46, DateTimeKind.Local)); 78 | 79 | b.Property("DepartmentId"); 80 | 81 | b.Property("FirstName") 82 | .IsRequired() 83 | .HasMaxLength(120); 84 | 85 | b.Property("JobPosition") 86 | .ValueGeneratedOnAdd() 87 | .HasDefaultValue(1); 88 | 89 | b.Property("LastName") 90 | .IsRequired() 91 | .HasMaxLength(120); 92 | 93 | b.Property("RecordStatus"); 94 | 95 | b.HasKey("Id"); 96 | 97 | b.HasIndex("DepartmentId"); 98 | 99 | b.ToTable("Employee"); 100 | }); 101 | 102 | modelBuilder.Entity("ManageEmployees.Models.Entities.Contract", b => 103 | { 104 | b.HasOne("ManageEmployees.Models.Entities.Employee", "Employee") 105 | .WithMany("Contracts") 106 | .HasForeignKey("EmployeeId"); 107 | }); 108 | 109 | modelBuilder.Entity("ManageEmployees.Models.Entities.Employee", b => 110 | { 111 | b.HasOne("ManageEmployees.Models.Entities.Department", "Department") 112 | .WithMany("Employees") 113 | .HasForeignKey("DepartmentId"); 114 | }); 115 | } 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/ManageEmployees/Migrations/ManageEmployeesContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Infrastructure; 4 | using Microsoft.EntityFrameworkCore.Metadata; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using ManageEmployees.Data; 7 | using ManageEmployees.Models.Enums; 8 | 9 | namespace ManageEmployees.Migrations 10 | { 11 | [DbContext(typeof(ManageEmployeesContext))] 12 | partial class ManageEmployeesContextModelSnapshot : ModelSnapshot 13 | { 14 | protected override void BuildModel(ModelBuilder modelBuilder) 15 | { 16 | modelBuilder 17 | .HasAnnotation("ProductVersion", "1.1.1") 18 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 19 | 20 | modelBuilder.Entity("ManageEmployees.Models.Entities.Contract", b => 21 | { 22 | b.Property("Id") 23 | .ValueGeneratedOnAdd(); 24 | 25 | b.Property("Amount"); 26 | 27 | b.Property("EmployeeId"); 28 | 29 | b.Property("EndDate") 30 | .ValueGeneratedOnAdd() 31 | .HasDefaultValue(new DateTime(2017, 3, 30, 11, 15, 22, 72, DateTimeKind.Local)); 32 | 33 | b.Property("Name") 34 | .IsRequired() 35 | .HasMaxLength(120); 36 | 37 | b.Property("RecordStatus"); 38 | 39 | b.Property("StartDate") 40 | .ValueGeneratedOnAdd() 41 | .HasDefaultValue(new DateTime(2017, 3, 30, 11, 15, 22, 71, DateTimeKind.Local)); 42 | 43 | b.HasKey("Id"); 44 | 45 | b.HasIndex("EmployeeId"); 46 | 47 | b.ToTable("Contract"); 48 | }); 49 | 50 | modelBuilder.Entity("ManageEmployees.Models.Entities.Department", b => 51 | { 52 | b.Property("Id") 53 | .ValueGeneratedOnAdd(); 54 | 55 | b.Property("Description") 56 | .IsRequired(); 57 | 58 | b.Property("Name") 59 | .IsRequired() 60 | .HasMaxLength(200); 61 | 62 | b.Property("RecordStatus"); 63 | 64 | b.HasKey("Id"); 65 | 66 | b.ToTable("Department"); 67 | }); 68 | 69 | modelBuilder.Entity("ManageEmployees.Models.Entities.Employee", b => 70 | { 71 | b.Property("Id") 72 | .ValueGeneratedOnAdd(); 73 | 74 | b.Property("BirthDate") 75 | .ValueGeneratedOnAdd() 76 | .HasDefaultValue(new DateTime(2017, 3, 30, 11, 15, 22, 46, DateTimeKind.Local)); 77 | 78 | b.Property("DepartmentId"); 79 | 80 | b.Property("FirstName") 81 | .IsRequired() 82 | .HasMaxLength(120); 83 | 84 | b.Property("JobPosition") 85 | .ValueGeneratedOnAdd() 86 | .HasDefaultValue(1); 87 | 88 | b.Property("LastName") 89 | .IsRequired() 90 | .HasMaxLength(120); 91 | 92 | b.Property("RecordStatus"); 93 | 94 | b.HasKey("Id"); 95 | 96 | b.HasIndex("DepartmentId"); 97 | 98 | b.ToTable("Employee"); 99 | }); 100 | 101 | modelBuilder.Entity("ManageEmployees.Models.Entities.Contract", b => 102 | { 103 | b.HasOne("ManageEmployees.Models.Entities.Employee", "Employee") 104 | .WithMany("Contracts") 105 | .HasForeignKey("EmployeeId"); 106 | }); 107 | 108 | modelBuilder.Entity("ManageEmployees.Models.Entities.Employee", b => 109 | { 110 | b.HasOne("ManageEmployees.Models.Entities.Department", "Department") 111 | .WithMany("Employees") 112 | .HasForeignKey("DepartmentId"); 113 | }); 114 | } 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/ManageEmployees/Migrations/20170330111522_Test.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using Microsoft.EntityFrameworkCore.Migrations; 4 | using Microsoft.EntityFrameworkCore.Metadata; 5 | 6 | namespace ManageEmployees.Migrations 7 | { 8 | public partial class Test : Migration 9 | { 10 | protected override void Up(MigrationBuilder migrationBuilder) 11 | { 12 | migrationBuilder.CreateTable( 13 | name: "Department", 14 | columns: table => new 15 | { 16 | Id = table.Column(nullable: false) 17 | .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), 18 | Description = table.Column(nullable: false), 19 | Name = table.Column(maxLength: 200, nullable: false), 20 | RecordStatus = table.Column(nullable: false) 21 | }, 22 | constraints: table => 23 | { 24 | table.PrimaryKey("PK_Department", x => x.Id); 25 | }); 26 | 27 | migrationBuilder.CreateTable( 28 | name: "Employee", 29 | columns: table => new 30 | { 31 | Id = table.Column(nullable: false) 32 | .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), 33 | BirthDate = table.Column(nullable: false, defaultValue: new DateTime(2017, 3, 30, 11, 15, 22, 46, DateTimeKind.Local)), 34 | DepartmentId = table.Column(nullable: false), 35 | FirstName = table.Column(maxLength: 120, nullable: false), 36 | JobPosition = table.Column(nullable: false, defaultValue: 1), 37 | LastName = table.Column(maxLength: 120, nullable: false), 38 | RecordStatus = table.Column(nullable: false) 39 | }, 40 | constraints: table => 41 | { 42 | table.PrimaryKey("PK_Employee", x => x.Id); 43 | table.ForeignKey( 44 | name: "FK_Employee_Department_DepartmentId", 45 | column: x => x.DepartmentId, 46 | principalTable: "Department", 47 | principalColumn: "Id", 48 | onDelete: ReferentialAction.Restrict); 49 | }); 50 | 51 | migrationBuilder.CreateTable( 52 | name: "Contract", 53 | columns: table => new 54 | { 55 | Id = table.Column(nullable: false) 56 | .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), 57 | Amount = table.Column(nullable: false), 58 | EmployeeId = table.Column(nullable: false), 59 | EndDate = table.Column(nullable: false, defaultValue: new DateTime(2017, 3, 30, 11, 15, 22, 72, DateTimeKind.Local)), 60 | Name = table.Column(maxLength: 120, nullable: false), 61 | RecordStatus = table.Column(nullable: false), 62 | StartDate = table.Column(nullable: false, defaultValue: new DateTime(2017, 3, 30, 11, 15, 22, 71, DateTimeKind.Local)) 63 | }, 64 | constraints: table => 65 | { 66 | table.PrimaryKey("PK_Contract", x => x.Id); 67 | table.ForeignKey( 68 | name: "FK_Contract_Employee_EmployeeId", 69 | column: x => x.EmployeeId, 70 | principalTable: "Employee", 71 | principalColumn: "Id", 72 | onDelete: ReferentialAction.Restrict); 73 | }); 74 | 75 | migrationBuilder.CreateIndex( 76 | name: "IX_Contract_EmployeeId", 77 | table: "Contract", 78 | column: "EmployeeId"); 79 | 80 | migrationBuilder.CreateIndex( 81 | name: "IX_Employee_DepartmentId", 82 | table: "Employee", 83 | column: "DepartmentId"); 84 | } 85 | 86 | protected override void Down(MigrationBuilder migrationBuilder) 87 | { 88 | migrationBuilder.DropTable( 89 | name: "Contract"); 90 | 91 | migrationBuilder.DropTable( 92 | name: "Employee"); 93 | 94 | migrationBuilder.DropTable( 95 | name: "Department"); 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | [Xx]64/ 19 | [Xx]86/ 20 | [Bb]uild/ 21 | bld/ 22 | [Bb]in/ 23 | [Oo]bj/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | artifacts/ 46 | 47 | *_i.c 48 | *_p.c 49 | *_i.h 50 | *.ilk 51 | *.meta 52 | *.obj 53 | *.pch 54 | *.pdb 55 | *.pgc 56 | *.pgd 57 | *.rsp 58 | *.sbr 59 | *.tlb 60 | *.tli 61 | *.tlh 62 | *.tmp 63 | *.tmp_proj 64 | *.log 65 | *.vspscc 66 | *.vssscc 67 | .builds 68 | *.pidb 69 | *.svclog 70 | *.scc 71 | 72 | # Chutzpah Test files 73 | _Chutzpah* 74 | 75 | # Visual C++ cache files 76 | ipch/ 77 | *.aps 78 | *.ncb 79 | *.opendb 80 | *.opensdf 81 | *.sdf 82 | *.cachefile 83 | *.VC.db 84 | 85 | # Visual Studio profiler 86 | *.psess 87 | *.vsp 88 | *.vspx 89 | *.sap 90 | 91 | # TFS 2012 Local Workspace 92 | $tf/ 93 | 94 | # Guidance Automation Toolkit 95 | *.gpState 96 | 97 | # ReSharper is a .NET coding add-in 98 | _ReSharper*/ 99 | *.[Rr]e[Ss]harper 100 | *.DotSettings.user 101 | 102 | # JustCode is a .NET coding add-in 103 | .JustCode 104 | 105 | # TeamCity is a build add-in 106 | _TeamCity* 107 | 108 | # DotCover is a Code Coverage Tool 109 | *.dotCover 110 | 111 | # NCrunch 112 | _NCrunch_* 113 | .*crunch*.local.xml 114 | nCrunchTemp_* 115 | 116 | # MightyMoose 117 | *.mm.* 118 | AutoTest.Net/ 119 | 120 | # Web workbench (sass) 121 | .sass-cache/ 122 | 123 | # Installshield output folder 124 | [Ee]xpress/ 125 | 126 | # DocProject is a documentation generator add-in 127 | DocProject/buildhelp/ 128 | DocProject/Help/*.HxT 129 | DocProject/Help/*.HxC 130 | DocProject/Help/*.hhc 131 | DocProject/Help/*.hhk 132 | DocProject/Help/*.hhp 133 | DocProject/Help/Html2 134 | DocProject/Help/html 135 | 136 | # Click-Once directory 137 | publish/ 138 | 139 | # Publish Web Output 140 | *.[Pp]ublish.xml 141 | *.azurePubxml 142 | 143 | # TODO: Un-comment the next line if you do not want to checkin 144 | # your web deploy settings because they may include unencrypted 145 | # passwords 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # NuGet Packages 150 | *.nupkg 151 | # The packages folder can be ignored because of Package Restore 152 | **/packages/* 153 | # except build/, which is used as an MSBuild target. 154 | !**/packages/build/ 155 | # Uncomment if necessary however generally it will be regenerated when needed 156 | #!**/packages/repositories.config 157 | # NuGet v3's project.json files produces more ignoreable files 158 | *.nuget.props 159 | *.nuget.targets 160 | 161 | # Microsoft Azure Build Output 162 | csx/ 163 | *.build.csdef 164 | 165 | # Microsoft Azure Emulator 166 | ecf/ 167 | rcf/ 168 | 169 | # Windows Store app package directory 170 | AppPackages/ 171 | BundleArtifacts/ 172 | 173 | # Visual Studio cache files 174 | # files ending in .cache can be ignored 175 | *.[Cc]ache 176 | # but keep track of directories ending in .cache 177 | !*.[Cc]ache/ 178 | 179 | # Others 180 | ClientBin/ 181 | [Ss]tyle[Cc]op.* 182 | ~$* 183 | *~ 184 | *.dbmdl 185 | *.dbproj.schemaview 186 | *.pfx 187 | *.publishsettings 188 | node_modules/ 189 | orleans.codegen.cs 190 | 191 | # RIA/Silverlight projects 192 | Generated_Code/ 193 | 194 | # Backup & report files from converting an old project file 195 | # to a newer Visual Studio version. Backup files are not needed, 196 | # because we have git ;-) 197 | _UpgradeReport_Files/ 198 | Backup*/ 199 | UpgradeLog*.XML 200 | UpgradeLog*.htm 201 | 202 | # SQL Server files 203 | *.mdf 204 | *.ldf 205 | 206 | # Business Intelligence projects 207 | *.rdl.data 208 | *.bim.layout 209 | *.bim_*.settings 210 | 211 | # Microsoft Fakes 212 | FakesAssemblies/ 213 | 214 | # GhostDoc plugin setting file 215 | *.GhostDoc.xml 216 | 217 | # Node.js Tools for Visual Studio 218 | .ntvs_analysis.dat 219 | 220 | # Visual Studio 6 build log 221 | *.plg 222 | 223 | # Visual Studio 6 workspace options file 224 | *.opt 225 | 226 | # Visual Studio LightSwitch build output 227 | **/*.HTMLClient/GeneratedArtifacts 228 | **/*.DesktopClient/GeneratedArtifacts 229 | **/*.DesktopClient/ModelManifest.xml 230 | **/*.Server/GeneratedArtifacts 231 | **/*.Server/ModelManifest.xml 232 | _Pvt_Extensions 233 | 234 | # LightSwitch generated files 235 | GeneratedArtifacts/ 236 | ModelManifest.xml 237 | 238 | # Paket dependency manager 239 | .paket/paket.exe 240 | 241 | # FAKE - F# Make 242 | .fake/ 243 | -------------------------------------------------------------------------------- /src/ManageEmployees/Controllers/EmployeeController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using ManageEmployees.Data.Abstract; 4 | using ManageEmployees.Models.Entities; 5 | using Microsoft.AspNetCore.Mvc; 6 | using Microsoft.AspNetCore.Cors; 7 | using ManageEmployees.Models.Enums; 8 | 9 | namespace ManageEmployees.Controllers 10 | { 11 | [Route("api/[controller]")] 12 | [EnableCors("AllowAll")] 13 | public class EmployeeController : Controller 14 | { 15 | private readonly IEmployeeRepository _employeeRepository; 16 | private readonly IContractRepository _contractRepository; 17 | private readonly IDepartmentRepository _departmentRepository; 18 | 19 | public EmployeeController(IEmployeeRepository employeeRepository, 20 | IContractRepository contractRepository, 21 | IDepartmentRepository departmentRepository) 22 | { 23 | this._employeeRepository = employeeRepository; 24 | this._contractRepository = contractRepository; 25 | this._departmentRepository = departmentRepository; 26 | } 27 | 28 | [HttpGet] 29 | public IActionResult Get() 30 | { 31 | var employees = _employeeRepository 32 | .AllIncluding(p => p.Department, c => c.Contracts) 33 | .Where(rs => rs.RecordStatus == RecordStatus.Active); 34 | 35 | if (employees.Any()) 36 | return Ok(employees); 37 | return NoContent(); 38 | } 39 | 40 | [HttpGet("{id}")] 41 | public IActionResult Get(int id) 42 | { 43 | var employee = _employeeRepository.GetSingle(p=>p.Id == id,dep=>dep.Department,con=>con.Contracts); 44 | if (employee != null) return Ok(employee); 45 | 46 | return NotFound(); 47 | } 48 | 49 | [HttpGet("{id}/contracts")] 50 | public IActionResult GetEmployeeContracts(int id) 51 | { 52 | var employeeContracts = _contractRepository.GetAll().Where(p => p.EmployeeId == id).Where(rs => rs.RecordStatus == RecordStatus.Active); 53 | 54 | if (employeeContracts != null) 55 | return Ok(employeeContracts); 56 | 57 | return NotFound(); 58 | } 59 | 60 | [HttpPost] 61 | public IActionResult Post([FromBody] dynamic employee) 62 | { 63 | try 64 | { 65 | var _employee = new Employee() 66 | { 67 | FirstName = employee.firstName, 68 | LastName = employee.lastName, 69 | BirthDate = employee.birthDate, 70 | JobPosition = (JobPosition)employee.jobPosition, 71 | DepartmentId = employee.departmentId 72 | }; 73 | 74 | if (_employee == null) throw new ArgumentNullException(nameof(_employee)); 75 | 76 | _employeeRepository.Add(_employee); 77 | _employeeRepository.Commit(); 78 | 79 | return Created($"/api/employee/", _employee); 80 | } 81 | catch (Exception ex) 82 | { 83 | return BadRequest(ex.Message); 84 | } 85 | } 86 | 87 | [HttpPut("{id}")] 88 | public void Put(int id, [FromBody] Employee employee) 89 | { 90 | try 91 | { 92 | var _employee = _employeeRepository.GetSingle(id); 93 | 94 | if (_employee == null) 95 | throw new ArgumentNullException(nameof(_employee)); 96 | 97 | _employee.FirstName = employee.FirstName; 98 | _employee.LastName = employee.LastName; 99 | _employee.BirthDate = employee.BirthDate; 100 | _employee.JobPosition = employee.JobPosition; 101 | _employee.RecordStatus = employee.RecordStatus; 102 | 103 | if (_departmentRepository.GetSingle(employee.DepartmentId) == null) 104 | throw new ArgumentNullException($"No departments exist with ID you have selected."); 105 | 106 | _employee.DepartmentId = employee.DepartmentId; 107 | _employeeRepository.Commit(); 108 | } 109 | catch (Exception ex) 110 | { 111 | throw new Exception(ex.Message); 112 | } 113 | } 114 | 115 | 116 | [HttpDelete("{id}")] 117 | public IActionResult Delete(int id) 118 | { 119 | Employee employee = _employeeRepository.GetSingle(id); 120 | 121 | if (employee == null) return new NotFoundResult(); 122 | 123 | var employeeContracts = _contractRepository.FindBy(a => a.EmployeeId == id); 124 | 125 | foreach (var contract in employeeContracts) 126 | _contractRepository.SetStatusDeleted(contract); 127 | 128 | _employeeRepository.SetStatusDeleted(employee); 129 | _employeeRepository.Commit(); 130 | 131 | return new NoContentResult(); 132 | } 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /src/ManageEmployees/Data/ManageEmployeesDbInitializer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using ManageEmployees.Models.Entities; 6 | using ManageEmployees.Models.Enums; 7 | 8 | namespace ManageEmployees.Data 9 | { 10 | public class ManageEmployeesDbInitializer 11 | { 12 | private static ManageEmployeesContext context; 13 | 14 | public static void Initialize(IServiceProvider serviceProvider) 15 | { 16 | context = (ManageEmployeesContext) serviceProvider.GetService(typeof (ManageEmployeesContext)); 17 | InitializeDatabase(); 18 | } 19 | 20 | private static void InitializeDatabase() 21 | { 22 | if (!context.Departments.Any()) 23 | { 24 | Department dpt1 = new Department { Name = "Development", Description= "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do tempor incididunt ut labore et dolore magna aliqua. This is supporting text.", RecordStatus = RecordStatus.Active }; 25 | Department dpt2 = new Department { Name = "Marketing", Description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do tempor incididunt ut labore et dolore magna aliqua. This is supporting text.", RecordStatus = RecordStatus.Active }; 26 | Department dpt3 = new Department { Name = "Consulting", Description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do tempor incididunt ut labore et dolore magna aliqua. This is supporting text.",RecordStatus = RecordStatus.Active }; 27 | 28 | context.Departments.Add(dpt1); //id=1 29 | context.Departments.Add(dpt2); //id=2 30 | context.Departments.Add(dpt3); //id=3 31 | 32 | context.SaveChanges(); 33 | } 34 | 35 | if (!context.Employees.Any()) 36 | { 37 | Employee emp1 = new Employee 38 | { 39 | FirstName = "Adam", 40 | LastName = "Abraham", 41 | BirthDate = DateTime.Now.Date.AddYears(-24), 42 | DepartmentId = 1, 43 | JobPosition = JobPosition.Junior, 44 | RecordStatus = RecordStatus.Active 45 | }; 46 | Employee emp2 = new Employee 47 | { 48 | FirstName = "Alexandra", 49 | LastName = "Allan", 50 | BirthDate = DateTime.Now.Date.AddYears(-23), 51 | DepartmentId = 1, 52 | JobPosition = JobPosition.Senior, 53 | RecordStatus = RecordStatus.Active 54 | }; 55 | Employee emp3 = new Employee 56 | { 57 | FirstName = "Bella", 58 | LastName = "Chapman", 59 | BirthDate = DateTime.Now.Date.AddYears(-20), 60 | DepartmentId = 2, 61 | JobPosition = JobPosition.Trainee, 62 | RecordStatus = RecordStatus.Active 63 | }; 64 | Employee emp4 = new Employee 65 | { 66 | FirstName = "Frank", 67 | LastName = "Clark", 68 | BirthDate = DateTime.Now.Date.AddYears(-30), 69 | DepartmentId = 3, 70 | JobPosition = JobPosition.Senior, 71 | RecordStatus = RecordStatus.Active 72 | }; 73 | context.Employees.Add(emp1); 74 | context.Employees.Add(emp2); 75 | context.Employees.Add(emp3); 76 | context.Employees.Add(emp4); 77 | context.SaveChanges(); 78 | } 79 | 80 | if (!context.Contracts.Any()) 81 | { 82 | Contract ct1 = new Contract 83 | { 84 | Name="Contract ct1", 85 | Amount = 50000, 86 | EmployeeId = 1, 87 | StartDate = DateTime.Now.Date, 88 | EndDate = DateTime.Now.Date.AddYears(2), 89 | RecordStatus = RecordStatus.Active 90 | }; 91 | 92 | Contract ct2 = new Contract 93 | { 94 | Name = "Contract ct2", 95 | Amount = 45000, 96 | EmployeeId = 1, 97 | StartDate = DateTime.Now.Date.AddYears(-3), 98 | EndDate = DateTime.Now.Date, 99 | RecordStatus = RecordStatus.Active 100 | }; 101 | Contract ct3 = new Contract 102 | { 103 | Name = "Contract ct3", 104 | Amount = 45000, 105 | EmployeeId = 1, 106 | StartDate = DateTime.Now.Date.AddYears(-3), 107 | EndDate = DateTime.Now.Date, 108 | RecordStatus = RecordStatus.Active 109 | }; 110 | Contract ct4 = new Contract 111 | { 112 | Name = "Contract ct4", 113 | Amount = 45000, 114 | EmployeeId = 2, 115 | StartDate = DateTime.Now.Date.AddYears(-3), 116 | EndDate = DateTime.Now.Date, 117 | RecordStatus = RecordStatus.Active 118 | }; 119 | Contract ct5 = new Contract 120 | { 121 | Name = "Contract ct5", 122 | Amount = 45000, 123 | EmployeeId = 3, 124 | StartDate = DateTime.Now.Date.AddYears(-3), 125 | EndDate = DateTime.Now.Date, 126 | RecordStatus = RecordStatus.Active 127 | }; 128 | 129 | context.Contracts.Add(ct1); 130 | context.Contracts.Add(ct2); 131 | context.Contracts.Add(ct3); 132 | context.Contracts.Add(ct4); 133 | context.Contracts.Add(ct5); 134 | 135 | context.SaveChanges(); 136 | } 137 | } 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /src/ManageEmployees/Project_Readme.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Welcome to ASP.NET Core 6 | 127 | 128 | 129 | 130 | 138 | 139 |
140 |
141 |

This application consists of:

142 |
    143 |
  • Sample pages using ASP.NET Core MVC
  • 144 |
  • Bower for managing client-side libraries
  • 145 |
  • Theming using Bootstrap
  • 146 |
147 |
148 | 160 | 172 |
173 |

Run & Deploy

174 | 179 |
180 | 181 | 184 |
185 | 186 | 187 | 188 | --------------------------------------------------------------------------------