https://github.com/alirizaadiyahsi/HaberSitesiV2
http://www.ext.net/
http://www.asp.net/mvc
http://www.lynda.com/ASPNET-tutorials/ASPNET-MVC-4-Essential-Training/109762-2.html?gfv=true
//Querying with LINQ to Entities using (var objCtx = new SchoolDBEntities()) { var schoolCourse = from cs in objCtx.Courses where cs.CourseName == "Course1" select cs; Course mathCourse = schoolCourse.FirstOrDefault<Course>(); IList<Course> courseList = schoolCourse.ToList<Course>(); string courseName = mathCourse.CourseName; }
//Querying with LINQ to Entities using (var objCtx = new SchoolDBEntities()) { var schoolCourse = from cs in objCtx.Courses where cs.CourseName == "Course1" select cs; Course mathCourse = schoolCourse.FirstOrDefault<Course>(); IList<Course> courseList = schoolCourse.ToList<Course>(); string courseName = mathCourse.CourseName; }
//Querying with native sql using (var objCtx = new SchoolDBEntities()) { //Inserting Student using ExecuteStoreCommand int InsertedRows = objCtx.ExecuteStoreCommand("Insert into Student(StudentName,StandardId) values('StudentName1',1)"); //Fetching student using ExecuteStoreQuery var student = objCtx.ExecuteStoreQuery<Student>("Select * from Student where StudentName = 'StudentName1'", null).ToList(); }
var student = (from s in ctx.Students where s.StudentName == "Student1" select s).FirstOrDefault<Student>();
var studentList = (from s in ctx.Students where s.StudentName == "Student1" select s).ToList<Student>();
var students = from s in ctx.Students groupby s.StandardId into studentsByStandard select studentsByStandard;
var student1 = from s in ctx.Students orderby s.StudentName ascending select s;
var projectionResult = from s in ctx.Students where s.StudentName == "Student1" select new { s.StudentName, s.Standard.StandardName, s.Courses };
using (var ctx = new SchoolDBEntities()) { stud = ctx.Students.Include(s => s.Standard) .Where(s => s.StudentName == "Student1").FirstOrDefault<Student>(); //you can also pass entity name as a string "Standard" // stud = ctx.Students.Include("Standard") .Where(s => s.StudentName == "Student1").FirstOrDefault<Student>(); }
using (var ctx = new SchoolDBEntities()) { stud = ctx.Students.Where(s => s.StudentName == "Student1") .Include(s => s.Standard.Teachers).FirstOrDefault(); }
using (var ctx = new SchoolDBEntities()) { ctx.Configuration.LazyLoadingEnabled = true; //Loading students only IList<Student> studList = ctx.Students.ToList<Student>(); Student std = studList[0]; //Loads Student address for particular Student only (seperate SQL query) StudentAddress add = std.StudentAddress; }
public SchoolDBEntities(): base("name=SchoolDBEntities") { this.Configuration.LazyLoadingEnabled = false; }
using (var ctx = new SchoolDBEntities()) { //Loading all students only IList<Student> studList = ctx.Students.ToList<Student>(); Student std = studList[0]; //Separate DB call to Load Standard for particular Student only (seperate SQL query) ctx.Entry(std).Reference(s => s.Standard).Load(); // Separate DB call to Load Courses for particular Student only (seperate SQL query) ctx.Entry(std).Collection(s => s.Courses).Load(); }
using (var ctx = new SchoolDBEntities()) { //Loading students only IList<Student> studList = ctx.Students.ToList<Student>(); Student std = studList[0]; //count courses without loading var CourseCount = ctx.Entry(std).Collection(s => s.Courses).Query().Count<Course>(); //Loads Courses for particular Student only (seperate SQL query) ctx.Entry(std).Collection(s => s.Courses).Query() .Where<Course>(c => c.CourseName == "New Course1").Load(); }
//Update entity using SaveChanges method using (SchoolEntities ctx = new SchoolDBEntities()) { var stud = (from s in ctx.Students where s.StudentName == "Student1" select s).FirstOrDefault(); stud.StudentName = "Student2"; int num = ctx.SaveChanges(); }
Student student = new Student(); student.StudentName = "Student1"; using (var ctx = new SchoolDBContext()) { ctx.Students.AddObject(student); ctx.SaveChanges(); }
using (var ctx = new SchoolDBContext()) { var stud = (from s in ctx.Students where s.StudentName == "Student1" select s).FirstOrDefault(); stud.StudentName = "Updated Student1"; int num = ctx.SaveChanges(); }
Student stud = null; using (SchoolDBContext ctx = new SchoolDBContext()) { ctx.ContextOptions.LazyLoadingEnabled = false; stud = (from s in ctx.Students where s.StudentName == " student1" select s).FirstOrDefault(); } //Out of using scope so ctx has disposed here stud.StudentName = "Updated student1"; using (SchoolDBContext newCtx = new SchoolDBContext()) { newCtx.Students.Attach(stud); newCtx.ObjectStateManager.ChangeObjectState(stud, System.Data.EntityState.Modified); newCtx.SaveChanges(); }
using (var ctx = new SchoolDBContext()) { var stud = (from s in ctx.Students where s.StudentName == "Student1" select s).FirstOrDefault(); ctx.Students.DeleteObject(stud); int num = ctx.SaveChanges(); }
Student stud = null; using (SchoolDBContext ctx = new SchoolDBContext()) { stud = (from s in ctx.Students where s.StudentName == "Student1" select s).FirstOrDefault(); } using (SchoolDBContext newCtx = new SchoolDBContext()) { newCtx.Students.Attach(stud); newCtx.Students.DeleteObject(stud); //you can use ObjectStateManager also //newCtx.ObjectStateManager.ChangeObjectState(stud, System.Data.EntityState.Deleted); int num = newCtx.SaveChanges(); }
public class SchoolDBContext: DbContext, IObjectContextAdapter { ObjectContext IObjectContextAdapter.ObjectContext { get { return (this as IObjectContextAdapter).ObjectContext; } } }
using (var ctx = new SchoolDBEntities()) { var stud = ctx.Students.Include(sadd => sadd.StudentAddress) .Where(s => s.StudentName == "Student1").FirstOrDefault<Student>(); stud.StudentName = "Changed Student Name"; string propertyName = ctx.Entry(stud).Property("StudentName").Name; string currentValue = ctx.Entry(stud).Property("StudentName").CurrentValue.ToString(); string originalValue = ctx.Entry(stud).Property("StudentName").OriginalValue.ToString(); bool isChanged = ctx.Entry(stud).Property("StudentName").IsModified; var dbEntity = ctx.Entry(stud).Property("StudentName").EntityEntry; }
using (var ctx = new SchoolDBEntities()) { var studentList = ctx.Students.SqlQuery("Select * from Student").ToList<Student>(); }
using (var ctx = new SchoolDBEntities()) { var studentName = ctx.Students.SqlQuery("Select studentid, studentname from Student where studentname='New Student1'").ToList(); }
using (var ctx = new SchoolDBEntities()) { //this will throw an exception var studentName = ctx.Students.SqlQuery("Select studentid as id, studentname as name from Student where studentname='New Student1'").ToList(); }
using (var ctx = new SchoolDBEntities()) { //Get student name of string type string studentName = ctx.Database.SqlQuery<string>("Select studentname from Student where studentid=1").FirstOrDefault<string>(); }
using (var ctx = new SchoolDBEntities()) { //Update command int noOfRowUpdated = ctx.Database.ExecuteSqlCommand("Update student set studentname ='changed student by command' where studentid=1"); //Insert command int noOfRowInserted = ctx.Database.ExecuteSqlCommand("insert into student(studentname) values('New Student')"); //Delete command int noOfRowDeleted = ctx.Database.ExecuteSqlCommand("delete from student where studentid=1"); }
protected override System.Data.Entity.Validation.DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, System.Collections.Generic.IDictionary<object, object> items) { if (entityEntry.Entity is Student) { if (entityEntry.CurrentValues.GetValue<string>("StudentName") == "") { var list = new ListDbValidationError
try { using (var ctx = new SchoolDBEntities()) { ctx.Students.Add(new Student() { StudentName = "" }); ctx.Standards.Add(new Standard() { StandardName = "" }); ctx.SaveChanges(); } } catch (DbEntityValidationException dbEx) { foreach (DbEntityValidationResult entityErr in dbEx.EntityValidationErrors) { foreach (DbValidationError error in entityErr.ValidationErrors) { Console.WriteLine("Error Property Name {0} : Error Message: {1}", error.PropertyName, error.ErrorMessage); } } }
// create new Standard entity object var newStandard = new Standard(); // Assign standard name newStandard.StandardName = "Standard 1"; //create DBContext object using (var dbCtx = new SchoolDBEntities()) { //Add standard object into Standard DBset dbCtx.Standards.Add(newStandard); // call SaveChanges method to save standard into database dbCtx.SaveChanges(); }
// create new student entity object var student = new Student(); // Assign student name student.StudentName = "New Student1"; // Create new StudentAddress entity and assign it to student entity student.StudentAddress = new StudentAddress() { Address1 = "Student1's Address1", Address2 = "Student1's Address2", City = "Student1's City", State = "Student1's State" }; //create DBContext object using (var dbCtx = new SchoolDBEntities()) { //Add student object into Student's EntitySet dbCtx.Students.Add(student); // call SaveChanges method to save student & StudentAddress into database dbCtx.SaveChanges(); }
//Create new standard var standard = new Standard(); standard.StandardName = "Standard1"; //create three new teachers var teacher1 = new Teacher(); teacher1.TeacherName = "New Teacher1"; var teacher2 = new Teacher(); teacher2.TeacherName = "New Teacher2"; var teacher3 = new Teacher(); teacher3.TeacherName = "New Teacher3"; //add teachers for new standard standard.Teachers.Add(teacher1); standard.Teachers.Add(teacher2); standard.Teachers.Add(teacher3); using (var dbCtx = new SchoolDBEntities()) { //add standard entity into standards entitySet dbCtx.Standards.Add(standard); //Save whole entity graph to the database dbCtx.SaveChanges(); }
//Create student entity var student1 = new Student(); student1.StudentName = "New Student2"; //Create course entities var course1 = new Course(); course1.CourseName = "New Course1"; course1.Location = "City1"; var course2 = new Course(); course2.CourseName = "New Course2"; course2.Location = "City2"; var course3 = new Course(); course3.CourseName = "New Course3"; course3.Location = "City1"; // add multiple courses for student entity student1.Courses.Add(course1); student1.Courses.Add(course2); student1.Courses.Add(course3); using (var dbCtx = new SchoolDBEntities()) { //add student into DBContext dbCtx.Students.Add(student1); //call SaveChanges dbCtx.SaveChanges(); }
Student stud ; // Get student from DB using (var ctx = new SchoolDBEntities()) { stud = ctx.Students.Where(s => s.StudentName == "New Student1").FirstOrDefault<Student>(); } // change student name in disconnected mode (out of DBContext scope) if (stud != null) { stud.StudentName = "Updated Student1"; } //save modified entity using new DBContext using (var dbCtx = new SchoolDBEntities()) { //Mark entity as modified dbCtx.Entry(stud).State = System.Data.EntityState.Modified; dbCtx.SaveChanges(); }
using (var dbCtx = new SchoolDBEntities()) { //Get existing StudentAddress for database for the student StudentAddress existingStudentAddress = dbCtx.StudentAddresses.AsNoTracking() .Where(addr => addr.StudentID == stud.StudentID).FirstOrDefault<StudentAddress>(); //Mark Student entity as modified dbCtx.Entry(stud).State = System.Data.EntityState.Modified; //Find whether StudentAddress is modified //if existing StudentAddress is not null then delete existing address if (existingStudentAddress != null) dbCtx.Entry<StudentAddress>(existingStudentAddress).State = System.Data.EntityState.Deleted; //if new StudentAddress is not null then add new StudentAddress. //This takes care modified address also. if (stud.StudentAddress != null) dbCtx.StudentAddresses.Add(stud.StudentAddress); dbCtx.SaveChanges(); }
using (var dbCtx = new SchoolDBEntities()) { //1- Get fresh data from database var existingStudent = dbCtx.Students.AsNoTracking().Include(s => s.Standard).Include(s => s.Standard.Teachers).Where(s => s.StudentName == "updated student").FirstOrDefault<Student>(); var existingTeachers = existingStudent.Standard.Teachers.ToList<Teacher>(); var updatedTeachers = teachers.ToList<Teacher>(); //2- Find newly added teachers by updatedTeachers (teacher came from client sided) - existingTeacher = newly added teacher var addedTeachers = updatedTeachers.Except(existingTeachers, tchr => tchr.TeacherId); //3- Find deleted teachers by existing teachers - updatedTeachers = deleted teachers var deletedTeachers = existingTeachers.Except(updatedTeachers, tchr => tchr.TeacherId); //4- Find modified teachers by updatedTeachers - addedTeachers = modified teachers var modifiedTeacher = updatedTeachers.Except(addedTeachers, tchr => tchr.TeacherId); //5- Mark all added teachers entity state to Added addedTeachers.ToList<Teacher>().ForEach(tchr => dbCtx.Entry(tchr).State = System.Data.EntityState.Added); //6- Mark all deleted teacher entity state to Deleted deletedTeachers.ToList<Teacher>().ForEach(tchr => dbCtx.Entry(tchr).State = System.Data.EntityState.Deleted); //7- Apply modified teachers current property values to existing property values foreach(Teacher teacher in modifiedTeacher) { //8- Find existing teacher by id from fresh database teachers var existingTeacher = dbCtx.Teachers.Find(teacher.TeacherId); if (existingTeacher != null) { //9- Get DBEntityEntry object for each existing teacher entity var teacherEntry = dbCtx.Entry(existingTeacher); //10- overwrite all property current values from modified teachers' entity values, //so that it will have all modified values and mark entity as modified teacherEntry.CurrentValues.SetValues(teacher); } } //11- Save all above changed entities to the database dbCtx.SaveChanges(); }
public static IEnumerableExcept (this IEnumerable items, IEnumerable other, Func getKey) { return from item in items join otherItem in other on getKey(item) equals getKey(otherItem) into tempItems from temp in tempItems.DefaultIfEmpty() where ReferenceEquals(null, temp) || temp.Equals(default(T)) select item; }
using (var dbCtx = new SchoolDBEntities()) { /* 1- Get existing data from database */ var existingStudent = dbCtx.Students.Include("Courses") .Where(s => s.StudentName == stud.StudentName).FirstOrDefault<Student>(); /* 2- Find deleted courses from student's course collection by students' existing courses (existing data from database) minus students' current course list (came from client in disconnected scenario) */ var deletedCourses = existingStudent.Courses.Except(stud.Courses, cours => cours.CourseId).ToList<Course>(); /* 3- Find Added courses in student's course collection by students' current course list (came from client in disconnected scenario) minus students' existing courses (existing data from database) */ var addedCourses = stud.Courses.Except(existingStudent.Courses, cours => cours.CourseId).ToList<Course>(); /* 4- Remove deleted courses from students' existing course collection (existing data from database)*/ deletedCourses.ForEach(c => existingStudent.Courses.Remove(c)); //5- Add new courses foreach(Course c in addedCourses) { /*6- Attach courses because it came from client as detached state in disconnected scenario*/ if (dbCtx.Entry(c).State == System.Data.EntityState.Detached) dbCtx.Courses.Attach(c); //7- Add course in existing student's course collection existingStudent.Courses.Add(c); } //8- Save changes which will reflect in StudentCourse table only dbCtx.SaveChanges(); }
using (var dbCtx = new SchoolDBEntities()) { //if already loaded in existing DBContext then use Set().Remove(entity) to delete it. var newtchr = dbCtx.Teachers.Where(t => t.TeacherName == "New teacher4") .FirstOrDefault<Teacher>(); dbCtx.Set(Teacher).Remove(newtchr); //Also, you can mark an entity as deleted //dbCtx.Entry(tchr).State = System.Data.EntityState.Deleted; //if not loaded in existing DBContext then use following. //dbCtx.Teachers.Remove(newtchr); dbCtx.SaveChanges(); }