Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write it pretty?

Hi i am new in c# and i want to ask how to write this code more prety

public void Update(Product pr)
    {
        Product prod = GeProductById(pr.ProductID);
        prod.Name       = pr.Name;
        prod.Count      = pr.Count;
        prod.InputPrice = pr.InputPrice;
        prod.InputDate  = pr.InputDate;
        prod.OutPrice   = pr.OutPrice;
        prod.InputPriceByCurrency   = pr.InputPriceByCurrency;
        prod.InputPriceCurrency     = pr.InputPriceCurrency;
        prod.ComeOwner  = pr.ComeOwner;
        prod.GroupID    = pr.GroupID;
        prod.Discount   = pr.Discount;

        _context.SubmitChanges();
    }

All it do just copy all properties except id. Can i write it shortly? Thanx and sorry for my bad english

like image 471
Sanja Melnichuk Avatar asked Dec 04 '10 15:12

Sanja Melnichuk


1 Answers

It seems like there's more to this. Why can't you save pr to the data store as is? It seems like you may be using the ORM inefficiently, though there could be good reason for this that we just can't see from the scope of this code.

On a more general note, you may have luck with something like automapper in cases like this. Though, honestly, I think with a little re-working of how you're using the ORM it shouldn't be necessary here.

Based on comments to far, I'd also like to note that there's nothing inherently wrong with a long and boring mapping function like this. Even if it's 20 properties or 200 properties. If it's only written once, is easy to read and understand what it's doing, does what it's doing well, etc. then it's not a bad piece of code. Code isn't always pretty, and it doesn't need to be. It's easy to be tempted to do something more clever to make the code cooler or more interesting, but clever isn't always better when it comes to supporting that code later.

like image 182
David Avatar answered Oct 14 '22 04:10

David