views:

23

answers:

1

I use ADO.NET Entity Framework with several data access layer methods that return the same domain entity. Let it be:

class PersonEntity {
  public int Id { get; set; }
  public string Name { get; set; }
}

and methods return Person entity by different criteria:

PersonEntity GetById(int id) {
  return db.Person.FirstOrDefault(x => new PersonEntity { Id = x.Id, Name = x.Name });
}

IQueryable<PersonEntity> GetByName(string name) {
  return db.Person.Where(x => x.Name == name).Select(x => new PersonEntity { Id = x.Id, Name = x.Name });
}

e.t.c. Code block x => new PersonEntity { Id = x.Id, Name = x.Name } is very repetitive (that is very annoying for many-fields entities) but I could not put it to a single point such as static method:

PersonEntity ConvertToPersonEntity(Person x) {
  return new PersonEntity { Id = x.Id, Name = x.Name }
}

Such external function call can't be translated into SQL operators. Is there any workaround here to keep conversion in one place?

Thank you in advance!

+3  A: 

Yes, you can do:

Expression<Func<Person, PersonEntity>> ConvertToPersonEntity() {
  return x => new PersonEntity { Id = x.Id, Name = x.Name };
}

...and then:

PersonEntity GetById(int id) {
  var exp = ConvertToPersonEntity();
  return db.Person.FirstOrDefault(exp);
}
Craig Stuntz
Thank you for the reply I'll check it tomorrow! It will be amazing if works!
Andrew Florko