'C#/Entity FrameWork'에 해당되는 글 1건

  1. 2016.04.29 데이터 생성과 호출
C#/Entity FrameWork2016.04.29 16:38


데이터 생성]


using (var ctx = new SchoolContext())

{

Student stud = new Student() { StudentName = "jangjeonghun" };

Standard standard = new Standard() { StandardName = "standardName" };                


ctx.Students.Add(stud);

ctx.Standards.Add(standard);


ctx.SaveChanges();

}




데이터 호출]


//Querying with LINQ to Entities 
using (var context = new SchoolDBEntities())
{
    var L2EQuery = context.Students.where(s => s.StudentName == "Bill");
        
    var student = L2EQuery.FirstOrDefault<Student>();

}


using (var context = new SchoolDBEntities())
{
    var L2EQuery = from st in context.Students
                    where st.StudentName == "Bill"
                    select st;
   
    var student = L2EQuery.FirstOrDefault<Student>();
    }


//Querying with Object Services and Entity SQL
string sqlString = "SELECT VALUE st FROM SchoolDBEntities.Students " +
                    "AS st WHERE st.StudentName == 'Bill'";
    
var objctx = (ctx as IObjectContextAdapter).ObjectContext;
                
ObjectQuery<Student> student = objctx.CreateQuery<Student>(sqlString);
                Student newStudent = student.First<Student>();


using (var con = new EntityConnection("name=SchoolDBEntities"))
{
    con.Open();
    EntityCommand cmd = con.CreateCommand();
    cmd.CommandText = "SELECT VALUE st FROM SchoolDBEntities.Students as st where st.StudentName='Bill'";
    Dictionary<int, string> dict = new Dictionary<int, string>();
    using (EntityDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.CloseConnection))
    {
            while (rdr.Read())
            {
                int a = rdr.GetInt32(0);
                var b = rdr.GetString(1);
                dict.Add(a, b);
            }
    }               
}


using (var ctx = new SchoolDBEntities())
{
    var studentName = ctx.Students.SqlQuery("Select studentid, studentname, standardId from Student where studentname='Bill'").FirstOrDefault<Student>();
}


using (var ctx = new SchoolDBEntities())
{
    var studentList = ctx.Students.SqlQuery("Select * from Student").ToList<Student>();
  
}





자료출처: http://www.entityframeworktutorial.net/Querying-with-EDM.aspx

             http://www.entityframeworktutorial.net/EntityFramework4.3/raw-sql-query-in-entity-framework.aspx

저작자 표시 비영리 동일 조건 변경 허락
신고

Posted by jangjeonghun

티스토리 툴바