Как добавить новый элемент в мою базу данных с 3 объединенными таблицами в EFCore / C#? - PullRequest
0 голосов
/ 01 апреля 2020

Я хочу добавить нового сотрудника в свою базу данных.

У меня есть SQL база данных с 3 таблицами: Компании, Команды, Сотрудники.

У меня есть список компаний в базе данных. У каждой компании есть несколько команд. В каждой команде несколько сотрудников.

Три таблицы объединены (я думаю, что это термин), и я использовал Entity Framework Core (для. NET Core 3.1), чтобы сделать это с подходом, основанным на коде. Сейчас я могу правильно заполнить список <> компаний, используя данные из моих таблиц SQL, используя одну строку кода. Отлично!

Допустим, я хотел добавить нового сотрудника, Остина, в отдел маркетинга Microsoft?

Как мне go узнать об этом?

Я не думаю, что могу просто добавить новую строку в таблицу Employee и ожидать, что она будет правильно соединена с таблицами Company и Team.

class Company
{
    [Key]
    int id; 
    string CompanyName;

    List<Team> Teams;
}
class Team
{
    [Key]
    int Id;
    string TeamName;

    List<Employee> Employees;
}
class Employee
{
    [Key]
    int Id;
    string EmployeeName;
}

void Main()
{
    // Context for my SQL database
    DbContext db = new DbContext();

    // Populate list of companies (and their respective teams and employees) from the SQL database
    List<Company> companies = db.Companies.Include(company => company.Teams).ThenInclude(team => team.Employees).ToList();

    // At this point 'companies' is populated and structured correctly. Each company in the list has a few teams. And each of those teams has a few employees. Great!

    // Let's say I want 'someEmployee' to be added to the Microsoft company's Marketing team

    // How do I add this employee to the database so that they are joined to the right company and team?
    Employee someEmployee = new Employee();

    // Code for adding the employee into the database here...
    // ...
}

1 Ответ

0 голосов
/ 01 апреля 2020

Пусть EF отслеживание изменения сущности сделает за вас работу:

static void Main()
{
    // Context for my SQL database
    MyDbContext db = new MyDbContext();

    // Populate list of companies (and their respective teams and employees) from the SQL database
    List<Company> companies = db.Companies.Include(company => company.Teams).ThenInclude(team => team.Employees).ToList();

    // At this point 'companies' is populated and structured correctly. Each company in the list has a few teams. And each of those teams has a few employees. Great!

    // Let's say I want 'someEmployee' to be added to the Microsoft company's Marketing team

    // How do I add this employee to the database so that they are joined to the right company and team?
    Employee someEmployee = new Employee()
    {
        Id = 1, // you probably will have your Ids auto-generated, my quick example didn't cater for that
        EmployeeName = "Austin"
    };

    var team = companies.Single(c => c.CompanyName == "Microsoft").Teams.Single(t => t.TeamName == "Microsoft Marketing"); // how you select the target team is not very important as long as it's been loaded by EF (which you do above)

    team.Employees.Add(someEmployee);
    db.Entry(someEmployee).State = EntityState.Added; // this is the only bit of work you have to do: tell EF change tracker this is a new entity so it should be inserted
    db.SaveChanges();

    // Code for adding the employee into the database here...
    // ...
}
...