2

I am having some problem about how to work with an entity say an EF entity and a surrogate type, which will be bound to the UI.

Suppose that I have following classes

    // Db Entity
    public class Car
    {
        public virtual int Id { get; set; }
        public string ChassisNumber { get; set; }
        public virtual string Brand { get; set; }
        public virtual string Name { get; set; }
    }

    // Surrogate type that reflects some properties of Car entity
    // This class will be bound to UI
    public class SurrogateCar
    {
        public string Brand { get; set; }
        public string Name { get; set; }
    }

Now I will be getting List<Car> from db and want to create a List<SurrogateCar> that represents my entities. I can do this easily in many ways, one of them like this:

      List<Car> cars = CarTable.GetMyCars(); // Just a dummy method, suppose it returns all entities from Db.

      List<SurrogateCar> surrogates = new List<SurrogateCar>();

      foreach (var car in cars)
      {
           surrogates.Add(new SurrogateCar { Brand = car.Brand, Name = car.Name });
      }

or I can write a custom cast method. But what I worry about is the performance. This method will be called frequently, so creating a list and populating it one by one seems a potential problem to me.

Do you have any better ways to do this, or is it okay to use it like this?

Thanks.

Mert Akcakaya
  • 3,109
  • 2
  • 31
  • 42

3 Answers3

2

If you have a web service, and that service is always going to return the SurrogateCar class, then you can write your entity query to return the class you want rather than getting the class you don't want:

var cars = from c in context.Cars where {your condition}
           select new SurrogateCar
           {
               Brand=c.Brand,
               Name=c.Name
           };

If, on the other hand you need the list of cars all the time, then as Roger pointed out AutoMapper is great! You just call

  CreateMap<Car, SurrogateCar>

then you just use Automapper to populate your new list:

  surrogates.AddRange(Map<IEnumberable<Car>, IEnumerable<SurrogateCar>>(cars));
SASS_Shooter
  • 2,186
  • 19
  • 30
1

Don't worry about the performance until you've really measured that's your bottleneck! Most probably these mappings between different types aren't that slow.

There are tools out there, eg AutoMapper http://automapper.org/ It's main purpose isn't performance though, but to potentially makes you write easier and less code.

Roger
  • 1,944
  • 1
  • 11
  • 17
0

I believe what you are really looking for is AutoMapper, it allows for seamless, easy code written around this situation. I would not worry too much about the performance unless you need to worry about it.

Here is a SO about mapping lists using automapper, also

Community
  • 1
  • 1
Justin Pihony
  • 66,056
  • 18
  • 147
  • 180