Creating Entities

First of all, Let's create some entities to have a test.

  1. Create a project
  2. Add following packages by NuGet
  • EntityFramework
  • MySql.Data.Entity (I'm just using MySql, it's not necessary)
  1. Add some codes:

     class Class
    {
    public int ClassId { get; set; } [MaxLength(50)]
    public string ClassName { get; set; } public virtual ICollection<Student> Students { get; set; }
    } class Student
    {
    public int StudentId { get; set; } [MaxLength(50)]
    public string StudentName { get; set; } public int Age { get; set; } public virtual Class Class { get; set; } public virtual ICollection<Course> Courses { get; set; } public virtual ICollection<Phone> Phones { get; set; }
    } class Phone
    {
    public int phoneId { get; set; } [MaxLength(20)]
    public string PhoneNumber { get; set; }
    } class Course
    {
    public int CourseId { get; set; } [MaxLength(50)]
    public string CourseName { get; set; } public virtual ICollection<Student> Students { get; set; }
    } class MyContext:DbContext
    {
    public MyContext():base("name=Test")
    { } public DbSet<Class> Classes { get; set; } public DbSet<Student> Students { get; set; } public DbSet<Course> Courses { get; set; }
    }
  2. Then, Execute following commands in NuGet command line

  • Enalbe-Migrations
  • Add-Migration init
  • Update-Database

Inserting

Add some codes in main function:

static void Main(string[] args)
{
Class class1 = new Class { ClassName = "Class One", }; Course course1 = new Course { CourseName = "English", }; Course course2 = new Course { CourseName = "Chinese", }; Student s1 = new Student
{
Age = 18,
Class = class1,
Courses = new List<Course> { course1, course2 },
Phones = new List<Phone> {
new Phone { PhoneNumber = "13718431702"},
new Phone { PhoneNumber = "13733423722" } },
StudentName = "Joye"
}; Student s2 = new Student
{
Age = 19,
Class = class1,
Courses = new List<Course> { course1 },
Phones = new List<Phone> {
new Phone { PhoneNumber = "13708431702"},
new Phone { PhoneNumber = "13783423722" } },
StudentName = "Ross"
}; Student s3 = new Student
{
Age = 17,
Class = class1,
Courses = new List<Course> { course2 },
Phones = new List<Phone> { new Phone { PhoneNumber = "13708431702" } },
StudentName = "Monnica"
}; using (MyContext db = new MyContext())
{
db.Students.Add(s1);
db.Students.Add(s2);
db.Students.Add(s3); db.SaveChanges();
}
}

I've created one class, two courses, three students and five phone numbers. Then, I add the three studengs to the Studengs DbSet and called the SaveChanges function. That all I did. Maybe you will say: Why don't we need to add all of the entities to the Dbset. When Entity Framework saves a entity, it also saves the whole object graph. How cool it is.

Querying

Filtering data in queries

using (MyContext db = new MyContext())
{
var students = db.Students.Where(s => s.Age > 17);
foreach (var item in students)
{
Console.WriteLine(item.StudentName + " " + item.Age);
}
}
Console.Read();

You can do this by LINQ too.

Sorting data in queries

using (MyContext db = new MyContext())
{
var students = db.Students
.OrderBy(s => s.Age)
.ThenBy(s => s.StudentName); foreach (var item in students)
{
Console.WriteLine(item.StudentName + " " + item.Age);
}
}
Console.Read();

Working with related entities

static void Main(string[] args)
{
using (MyContext db = new MyContext())
{
var students = from s in db.Students
where s.Courses.Any(c => c.CourseName == "Chinese")
select s; foreach (var item in students)
{
Console.WriteLine(item.StudentName + " " + item.Age);
}
} Console.Read();
}

Loading Related Entities

there are three ways of loading related entities:

Lazy Loading

This way is the default way of Entity Framework 6. Lazy loading is the process whereby an entity or collection of entities is automatically loaded from the database the first time that a property referring to the entity/entities is accessed.(MSND) There are two rules you must pay attention to:

  1. The model must be defined as public
  2. the navigation property must be defined as virtual

For example:

using (MyContext db = new MyContext())
{
Student oneStudent = db.Students.Find(1); //query the database for the first time
foreach (var item in oneStudent.Phones) //query the database for the second time
{
Console.WriteLine(item.PhoneNumber);
}
}

You can turn lazy loading off by two ways:

  1. Remove the public key of model or remove the virtual key of navigation property
  2. Set the Configuration.LazyLoadingEnabled property of DbContext flase

Eagerly Loading

Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query. Eager loading is achieved by use of the Include method.(MSND) For example:

using (MyContext db = new MyContext())
{
db.Configuration.LazyLoadingEnabled = false; var students = from s in db.Students.Include(s => s.Phones)
where s.StudentName == "Joye"
select s; foreach (var s in students)
{
foreach (var p in s.Phones)
{
Console.WriteLine(p.PhoneNumber);
}
}
}

using (MyContext db = new MyContext())
{
db.Configuration.LazyLoadingEnabled = false; var courses = from c in db.Courses.Include(cc => cc.Students.Select(s => s.Phones))
where c.CourseName == "English"
select c; Console.WriteLine(courses.First().Students.First().Phones.First().PhoneNumber);
}

Explicitly Loading

Even with lazy loading disabled it is still possible to lazily load related entities, but it must be done with an explicit call. To do so you use the Load method on the related entity’s entry.(MSND) For example:

using (MyContext db = new MyContext())
{
db.Configuration.LazyLoadingEnabled = false; Course c = db.Courses.Find(1);
db.Entry(c)
.Collection(cc => cc.Students)
.Load(); Console.WriteLine(c.Students.Count);
}

If the navigation property is a single entity, please use Reference method. If the navigation property is a collection of entities, please use method Collection.

Updating

using (MyContext db = new MyContext())
{
var sutdent = db.Students.Find(1);
sutdent.StudentName = "Joey";
db.SaveChanges();
}

Or:

using (MyContext db = new MyContext())
{
var sutdent = new Student
{
StudentId = 1,
StudentName = "Joeyy"
}; db.Entry(sutdent).State = EntityState.Modified;
db.SaveChanges();
}

Deleting

using (MyContext db = new MyContext())
{
var student = db.Students.Find(1);
var course = db.Courses.Find(1); course.Students.Remove(student);
db.SaveChanges();
}

After you run the codes, one of the rows of table coursestudents is deleted. If you remove a entity from db.Students, one of the rows of table people will be deleted.

You can also use entry method:

using (MyContext db = new MyContext())
{
var phone = new Phone { phoneId = 1 };
db.Entry(phone).State = EntityState.Deleted;
db.SaveChanges();
}

That's all.

Lerning Entity Framework 6 ------ Inserting, Querying, Updating, and Deleting Data的更多相关文章

  1. Lerning Entity Framework 6 ------ Defining Relationships

    There are three types of relationships in database. They are: One-to-Many One-to-One Many-to-Many Th ...

  2. MySQL Crash Course #11# Chapter 20. Updating and Deleting Data

    INDEX Updating Data The IGNORE Keyword Deleting Data Faster Deletes Guidelines for Updating and Dele ...

  3. Lerning Entity Framework 6 ------ Handling concurrency With SQL Server Database

    The default Way to handle concurrency of Entity Framework is using optimistic concurrency. When two ...

  4. Lerning Entity Framework 6 ------ Working with in-memory data

    Sometimes, you need to find some data in an existing context instead of the database. By befault, En ...

  5. Lerning Entity Framework 6 ------ Defining the Database Structure

    There are three ways to define the database structure by Entity Framework API. They are: Attributes ...

  6. Lerning Entity Framework 6 ------ Introduction to TPH

    Sometimes, you have created two models. They have the same parent class like this: public class Pers ...

  7. Entity Framework优化一:引发了“System.Data.Entity.Core.EntityCommandExecutionException”类型的异常

    错误信息: “System.Data.Entity.Core.EntityCommandExecutionException”类型的异常在 EntityFramework.SqlServer.dll ...

  8. Lerning Entity Framework 6 ------ Complex types

    Complex types are classes that map to a subset of columns of a table.They don't contains key. They a ...

  9. Lerning Entity Framework 6 ------ Using a commandInterceptor

    Sometimes, We want to check the original sql statements. creating a commandInterceptor is a good way ...

随机推荐

  1. IOS初级:UIwindow

    AppDelegate.h @property (strong, nonatomic) UIWindow *window; AppDelegate.m - (BOOL)application:(UIA ...

  2. 纯H5+c3实现表单验证

    客户端验证是网页客户端程序最常用的功能之一,我们之前使用了各种各样的js库来进行表单的验证.HTML5其实早已为我们提供了表单验证的功能.至于为啥没有流行起来估计是兼容性的问题还有就是样式太丑陋了吧. ...

  3. 2017/2/5:oracle数据库的三大文件

    oracle的三大文件: 一:控制文件:控制文件是一个小型的二进制文件,可以记录数据库的物理结构.包括:     * 数据库名称     * 数据文件和日志文件的名称和位置     * 数据库创建的时 ...

  4. Java语法基础课 原码 反码 补码

    原码就是符号位加上真值的绝对值, 即用第一位表示符号, 其余位表示值. 反码的表示方法是:正数的反码是其本身:负数的反码是在其原码的基础上, 符号位不变,其余各个位取反. 补码的表示方法是在反码的基础 ...

  5. 如何将spring boot项目打包成war包

    一.修改打包形式 在pom.xml里设置 <packaging>war</packaging> 二.移除嵌入式tomcat插件 在pom.xml里找到spring-boot-s ...

  6. UOJ 117 欧拉回路(套圈法+欧拉回路路径输出+骚操作)

    题目链接:http://uoj.ac/problem/117 题目大意: 解题思路:先判断度数: 若G为有向图,欧拉回路的点的出度等于入度. 若G为无向图,欧拉回路的点的度数位偶数. 然后判断连通性, ...

  7. PHP时间范围:本周、本月、下月等简写

    在阅读TP5.1源码,发现其在时间范围上的写法很特别,个人第一次见,做一次记录 $timeRule = [ 'today' => ['today', 'tomorrow'], 'yesterda ...

  8. 第07章:MongoDB-CRUD操作--文档--创建

    ①语法 insert() save()  --有修改没有新增 insertOne() [3.2版本新增]向指定集合中插入一条文档数据 insertMany() [3.2版本新增]向指定集合中插入多条文 ...

  9. eclipse中tomcat启动设置参数

      今天新接触一个项目,使用java+flex做的单机项目,由于模块太多,打成war后就有300M左右了.所以,启动的时候,比较慢,超过了e eclipse中默认的45s,当我进行修改启动事件后,有一 ...

  10. laravel 5.1 使用Eloquent ORM 操作实例

    Laravel 的 Eloquent ORM 提供了更优雅的ActiveRecord 实现来和数据库的互动. 每个数据库表对应一个模型文件. 数据库配置 .env文件(也可以直接修改config/da ...