C# how to save the same data structure into different data tables.

  • Thread starter Thread starter zydjohn
  • Start date Start date
Z

zydjohn

Guest
I have one data structure class, it is used to represent 3 different type of people, the total employees, the employees working for today, and the employees not working for today.

The following is my code so far:

public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime ReportDate { get; set; }
}

public class ObjComparer : IEqualityComparer<Employee>
{
public bool Equals(Employee x, Employee y)
{
if (x.ID.Equals(y.ID))
{
return true;
}
else
{
return false;
}
}

public int GetHashCode(Employee obj)
{
unchecked
{
int hash = 100;
hash = hash * 10 + obj.ID.GetHashCode();
return hash;
}
}
}


static void Main(string[] args)
{
List<Employee> All_Employees = new List<Employee>();
All_Employees.Add(new Employee { ID = 1, Name = "A", ReportDate = new DateTime(2018, 01, 01) });
All_Employees.Add(new Employee { ID = 2, Name = "B", ReportDate = new DateTime(2018, 01, 01) });
All_Employees.Add(new Employee { ID = 3, Name = "C", ReportDate = new DateTime(2018, 01, 01) });
List<Employee> Attendees = new List<Employee>();
Attendees.Add(new Employee { ID = 1, Name = "A", ReportDate = DateTime.Today });
Attendees.Add(new Employee { ID = 2, Name = "B", ReportDate = DateTime.Today });
List<Employee> Absentees = new List<Employee>();
}


I have the following 3 database tables in SQL Server 2017 database: db1, the following is the data table definitions:

CREATE TABLE [dbo].[Employees](
[ID] [int] NOT NULL,
[Name] [nvarchar](100) NOT NULL,
[ReportDate] [Datetime] NOT NULL,
CONSTRAINT PK_Employees PRIMARY KEY(ID))

CREATE TABLE [dbo].[Attendees](
[ID] [int] NOT NULL,
[Name] [nvarchar](100) NOT NULL,
[ReportDate] [Datetime] NOT NULL,
CONSTRAINT PK_Attendees PRIMARY KEY(ID))

CREATE TABLE [dbo].[Absentees](
[ID] [int] NOT NULL,
[Name] [nvarchar](100) NOT NULL,
[ReportDate] [Datetime] NOT NULL,
CONSTRAINT PK_Absentees PRIMARY KEY(ID))



I have one piece of code to save records in data table using Microsoft.EntityFrameworkCore:

public static void Save_People(List<Employee> People)
{
if (People.Count >= 1)
{
using (DBContext context = new DBContext())
{
context.People.AddRange(People);
try
{
context.SaveChanges();
}
catch (Exception ex)
{
Console.WriteLine("Exception: {0}!", ex.Message);
}
}
}
People.Clear();
}




Now, I have 2 issues to solve: First, how I can use something like All_Employees.Except(Attendees) to get Absentees.

Second, how I can save 3 different kind of people into their respective data tables using one save records function with some parameters but the same class definition <employee>? Do I have to write 3 save records functions for different type of records?

Please advise,

Continue reading...
 
Back
Top