Haavali
Haavali

Reputation: 221

How to copy objects of Different classes which has same attributes?

Good day friends!

I have 2 model classes say Page and PageHistory. both contains same attributes. Here whenever I edit a Page object, I need to update PageHistory object with same property values.

I tried something like this:

[HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(Page page, FormCollection frm)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    page.IsPublished = !string.IsNullOrEmpty(frm["BtnPublish"]);
                    _db.Entry(page).State = EntityState.Modified;
                    _db.SaveChanges();

                    //Add updated page in hitory, if something is modified
                    PageHistory ph=new PageHistory();
                    ph.ID=page.ID
                    // likewise all attributes.....
                    // after all values are assigned, save a History object
                    ph.SaveChanges();

                    return RedirectToAction("Subpages", new { id = page.ParentId });
                }
            }
            catch (DataException)
            {
                //Log the error (add a variable name after DataException)
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator (http://support.mysite.com).");
            }
            return View(page);
        }

It is working, But this is not so optimized, is there any alternatives available to copy objects? and one more question is, Is it possible to Inherit the PageHistory class from Page class, because both contains same attributes? which one is the best approach?

Upvotes: 0

Views: 338

Answers (1)

Vladislav Qulin
Vladislav Qulin

Reputation: 1942

  1. I would recommend you to use the same model for same data presentation.

  2. I would recommend you to create inherit class PageHistory. It will allow you to cast Page to PageHistory like:

    (PageHistory) page;
    
  3. I would recommend you to incapsulate that PageHistory props copying behind interface like:

    public interface IPageHistoryBuilder
    {
        PageHistory Build(Page page);
    }
    
    public class PageHistoryBuilder : IPageHistoryBuilder
    {
        public PageHistory Build(Page page)
        {
            return new PageHistory
            {
                // copy ALL the props here
            }
        }
    }
    

Your code will look like:

if (ModelState.IsValid)
{
    page.IsPublished = !string.IsNullOrEmpty(frm["BtnPublish"]);
    _db.Entry(page).State = EntityState.Modified;
    _db.SaveChanges();

    var ph = pageHistoryBuilder.Build(page);
    ph.SaveChanges();
// and so long
}

And don't forget about declaring the builder in controller constructor:

public class YourController : Controller
{
     private readonly IPageHistoryBuilder pageHistoryBuilder;
     public YourController(IPageHistoryBuilder pageHistoryBuilder)
     {
         this.pageHistoryBuilder = pageHistoryBuilder;
     }
}

Upvotes: 2

Related Questions