tags:

views:

258

answers:

1

Is there an easy way to take a DataTable and cast it to its entity type?

I have an Entity called Samples, however through layering this is at one point returned as a DataTable - i woud like to be able to cast this to its entity type if possible?

Thanks

A: 

you probably cannot cast, as most probably your entity has no inheritance relation with DataRow (or DataTable, whatever).

Assuming

class Post {
  public int Id {get; private set;}
  public string Title {get; set;}
  public Post(int id) { Id=id;}
}

you'd want something like

foreach (var row in dataTable.Rows) {
  posts.Add(new Post(Convert.ToInt32(row[0])) { Title = row[1].ToString()} ;
}

not fun, I agree. that's what NHibernate (and the younger brother Entity Framework and it's cousin Linq2SQL ) are for.

Ken Egozi