开发者

EF: Can I have single point for lambda to class instance conversion?

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!


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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜