c# - how to put items in entity classes for multiple tables -
i'm beginner working asp.net entity framework database first.
there 2 tables need take data from, , 2 class entities entity framework created already. have code below.
using (project_dbentities context=new project_dbentities()) { list<firstinternship> lst=new list<firstinternship>(); lst = context.firstinternships.sqlquery("select * firstinternships ").tolist<firstinternship>(); repeater1.datasource = lst; repeater1.databind(); }
this code brings firstinternship table items. have fields in student table. changed code below dont know how hold fields in classes when joining tables.
using (project_dbentities context=new project_dbentities()) { list<firstinternship> lst=new list<firstinternship>(); lst = context.firstinternships.sqlquery("select * firstinternships f join students s on s.id=fi.studentid").tolist<firstinternship>(); repeater1.datasource = lst; repeater1.databind(); }
here, need create third class myself? or how use entity classes if want hold multiple table items in classes? proper way?
firstly, entity framework object relational mapper (orm). maps relational database entities (say: tables) objects (as in object oriented entities).
your project_dbentities
class should contain properties of type dbset<t>
can access model classes (like firstinternship
) without writing single line of sql. first code snippet like...
using (var context = new project_dbentities()) { // it's useless initialize lst variable new list var lst = context.firstinternships // no need write sql .tolist(); // no need specify type repeater1.datasource = lst; repeater1.databind(); }
then in model classes find navigation properties firstinternship.students
. these navigation properties allow access associated entities without explicitly writing joins. not in sql, not in linq code. like...
using (var context = new project_dbentities()) { var lst = f in context.firstinternships s in f.students select new { internship = f.name, sudent = s.name }; repeater1.datasource = lst; repeater1.databind(); }
what follows after select new
you. depends on want show in repeater. recommended create view model or dto classes purpose:
select new studentdto { internship = f.name, sudent = s.name, .... }
Comments
Post a Comment