1

I have 2 tables like below. am using DB first approch

public class Team
{
    public long Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

public class Employee
{
    public long Id { get; set; }
    public long TeamId { get; set; } // foreign key reference fom Team table
    public string Name { get; set; }
    public long ReferedBy { get; set; } // foreign key reference fom employee table
}

now i have to insert data to both table once. for example i need to insert data like below.

enter image description here

before introducing Referred By column i was using below code to insert.

        Team team = new Team();
        team.Name = "Team1";
        team.Description = "Some Description";

        Employee E1 = new Employee();
        E1.Name = "Jon";
        Employee E2 = new Employee();
        E2.Name = "Harish";

        team.Employee.Add(E1);
        team.Employee.Add(E2);

        DBEntity db = new DBEntity();
        db.Set<Team>().add(team);
        db.saveChanges();

after introducing Referred By Column how i can insert these reference to database.

Venki
  • 68
  • 1
  • 7

3 Answers3

0

public long TeamId { get; set; } // foreign key reference fom Team table

You need one-to-one relationship see my post:

http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx

before introducing Referred By column i was using below code to insert.

You need here Self Referencing Entity:

EF self one-to-many relationship

Bassam Alugili
  • 16,345
  • 7
  • 52
  • 70
0

If you need to execute the insertion as bulk insert and the id of the Employee table is an identity column, you have to call the SaveChanges() twice to get the identity value from db so that you set emp2.ReferredBy=emp1.id;

If your requirement to hit the db in one hit, you have two options 1. Use a transaction and call SaveChanges twice where a failure occurs the transaction roll back. 2. Build your own identity technique and stop identity in db.

Check Get identity before SaveChanges

Community
  • 1
  • 1
Mahmoud Shaaban
  • 122
  • 1
  • 4
  • 13
0

EF Core takes care of everything, we don't need to worry, here is my working code to insert in different tables, even multiple records

Code in service to insert multiple tables :

public async Task<Customer> AddCustomerAsync(Customer customer)
{
    await AppContext.Customers.AddAsync(customer);

    // Add Multiple addresses
    if(customer.Addresses != null && customer.Addresses.Count > 0)
        foreach(var address in customer.Addresses)
            await AppContext.Addresses.AddAsync(address);

    // Add multiple contacts
    if(customer.Contacts != null && customer.Contacts.Count > 0)
        foreach(var contact in customer.Contacts)
            await AppContext.Contacts.AddAsync(contact);

    await AppContext.SaveChangesAsync();
    return customer;
}

JSON which I post to my WebAPI:

{
  "customerId": 0,
  "firstName": "John",
  "lastName": "Smith",
  "customerType": 102,
  "addresses": [
    {
      "addressId": 0,
      "street": "101 New Friends Colony",
      "city": "New Delhi",
      "stateId": 30,
      "country": "India",
      "zipCode": "110025",
      "isDefault": true
    }
  ],
  "contacts": [
    {
      "contactId": 0,
      "phone": "9873198766",
      "email": "testmail@gmail.com",
      "isDefault": true,
      "customerId": 0
    }
  ]
}

Controller is just calling the service:

[HttpPost]
[Route("AddCustomer")]
public async Task<bool> AddCustomerAsync(Customer customer)
{
   await CustService.AddCustomerAsync(customer);
   return true;
}

Finally Customer Model:

public class Customer
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Display(Name ="Customer Id")]
    public int CustomerId { get; set; }
    [MaxLength(20)]
    public string FirstName { get; set; } = string.Empty;
    [MaxLength(20)]
    public string LastName { get; set; } = string.Empty;
    public CustomerType CustomerType { get; set; }
    public virtual ICollection<Address> Addresses { get; set; } = new List<Address>();
    public virtual ICollection<Contact> Contacts { get; set; } = new List<Contact>();
}
Ali Adravi
  • 21,707
  • 9
  • 87
  • 85