locked
Design Entity relationship with cloning option on Entity object. RRS feed

  • Question

  • Scenario : I have Four Entities with properties and relationship as mentioned  below.

    Resource(ResourceID(PK), ResourceType, EmployeeNav)
    Employee (EMPID(PK), FName, LName, ResourceID(FK), AddressID (FK), AddressNav, ResourceNav)
    Address (AddressID(PK), Add1, Add2, PhoneID(FK), EmployeeNav, PhoneNav)
    Phone (PhoneID, EMPID HasOptional(FK Nullable))

    Requirement is to clone (copy) Resource Entity.
    Problem : Not able to clone/duplicate/copy Entity with newly generated keys, for Null able FK column relation.

    Method followed
    1.Initialize Resouce object
    2.Using reflection, Loop though properties of Resouce object, navigate to Employee Entity on EmployeeNav property
    3.Set EmployeeID (PK) property to 0.
    3.Loop through Employee and find ResourceID (FK) and set ResourceID to 0.
    4.Navigate to Address Entity... follow same pattern
    5.Reach Phone.
    6.Using back navigation properties i.e. EmployeeNav, ResourceNav to Resource Enitity.

    Note : Applying TrackingState = TrackingState.Added on each entity.

    7. adding Object To Context and Upon _context.SaveChanges() 

    I am able to clone/ copy all Entites with new PK/FK ids, except Phone Entity.
    Problem : I am not able to fill EMPID of Phone Entity with new cloned EMPID instead it contains original(parent) Resource Entity's EMPID.

    Please let me know if any one has directions/inputs for this problem.

    Thanks in advance!!



    Monday, May 30, 2016 3:14 PM

Answers

  • Hi Sheshagiri H,

    According to your description, Do you mean that you retrieve a Resouce object from database, then clone entity with relationships and save it into database? if so, you could use AsNotracking method to achieve it. and I create a similar demo as below for your reference.

    using (var db = new BloggingEntities())
    {
       // Fetch a detached Blog and populate its Posts.
       var blog = db.Blogs.Include("Posts").AsNoTracking().Where(b => b.BlogId == 2).FirstOrDefault();
    
        db.Blogs.Add(blog);
        db.SaveChanges();
    }

    Best regards,

    Cole Wu


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Tuesday, May 31, 2016 5:17 AM