Hi,
I am working on a requirement. So, basically there are three entities in EF and lets consider them as:
1) Employee Table (2) Primary_Address Table (3) Secondary_Address Table
Here, Primary_Address Table and Secondary_Address Table are in 1-1 relationship with Employee Table.
I want to create a clone of Employee along with its child objects - Primary_Address and Secondary_Address.
Am using "Deep Cloning" using ICloneable interface. I can be able to clone the "Employee" object but the child objects are always NULL.
What I have tried:
Employee Entity Structure:
;
[Table("Employee")]
public class EmployeeEntity : ICloneable
{
[Key]
[Column("Id")]
public int Id { get; set; }
[Column("EmployeeName")]
public string EmployeeName { get; set; }
public PrimaryAddressEntity PrimaryAddress { get; set; }
public SecondaryAddressEntity SecondaryAddress { get; set; }
public EmployeeEntity Clone() { return (EmployeeEntity)this.MemberwiseClone(); }
object ICloneable.Clone() { return Clone(); }
}
Primary Address Entity Structure:
[Table("PrimaryAddress")]
public class PrimaryAddressEntity
{
[Key]
[Column("PrimaryAddrId")]
public int PrimaryAddrId { get; set; }
[Key]
[Column("PrimaryAddrDesc")]
public string PrimaryAddrDesc { get; set; }
[Column("EmployeeId")]
public int EmployeeId { get; set; }
[ForeignKey("EmployeeId")]
public EmployeeEntity Employee { get; set; }
}
Secondary Address Entity Structure:
[Table("SecondaryAddress")]
public class SecondaryAddressEntity
{
[Key]
[Column("SecondaryAddrId")]
public int SecondaryAddrId { get; set; }
[Key]
[Column("SecondaryAddrDesc")]
public string SecondaryAddrDesc { get; set; }
[Column("EmployeeId")]
public int EmployeeId { get; set; }
[ForeignKey("EmployeeId")]
public EmployeeEntity Employee { get; set; }
}
Now, in "cloning" operation, am doing like this to test if everything is working fine or not:
EmployeeEntity testObj = FetchEmployee("100");
EmployeeEntity cloneTestObj = testObj.Clone();
cloneTestObj.Id = 0;
cloneTestObj.EmployeeName = "Agnib";
AddEmployee(cloneTestObj);
public EmployeeEntity FetchEmployee(string empId)
{
return dbContext.Employees.Where(e => e.Id == System.Convert.ToInt32(empId)).Include(p=>p.PrimaryAddress).Include(s=>s.SecondaryAddress).FirstOrDefault();
}
public bool AddEmployee(EmployeeEntity employeeEntity)
{
dbContext.Employees.Add(employeeEntity);
return dbContext.SaveChanges() > 0;
}
In this approach, I can be able to create a clone of the Employee object but the child objects (PrimaryAddress and SecondaryAddress) are coming as NULL while am fetching on the basis of EmployeeId.
I must be doing something wrong but cannot be able to figure it out.
So, if anyone can help me in this.
Thank you all.
Take care.