Lerning Entity Framework 6 ------ Inserting, Querying, Updating, and Deleting Data
Creating Entities
First of all, Let's create some entities to have a test.
- Create a project
- Add following packages by NuGet
- EntityFramework
- MySql.Data.Entity (I'm just using MySql, it's not necessary)
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; }
}
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:
- The model must be defined as public
- 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:
- Remove the public key of model or remove the virtual key of navigation property
- 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的更多相关文章
- 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 ...
- 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 ...
- 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 ...
- 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 ...
- Lerning Entity Framework 6 ------ Defining the Database Structure
There are three ways to define the database structure by Entity Framework API. They are: Attributes ...
- Lerning Entity Framework 6 ------ Introduction to TPH
Sometimes, you have created two models. They have the same parent class like this: public class Pers ...
- Entity Framework优化一:引发了“System.Data.Entity.Core.EntityCommandExecutionException”类型的异常
错误信息: “System.Data.Entity.Core.EntityCommandExecutionException”类型的异常在 EntityFramework.SqlServer.dll ...
- 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 ...
- Lerning Entity Framework 6 ------ Using a commandInterceptor
Sometimes, We want to check the original sql statements. creating a commandInterceptor is a good way ...
随机推荐
- .net从网络接口地址获取json,然后解析成对象(一)
整理代码,今天遇到一个问题,就是从一个场景接口获取json,然后解析成对象.之前的时候都好好的,这次返回的json字符串里,由于字符编码的问题,格式上不能转换.一直以为是解析的过程编码有误,试了utf ...
- centos配置虚拟用户再也不用那么麻烦了
http://wiki.centos.org/HowTos/Chroot_Vsftpd_with_non-system_users yum install -y vsftpd db4-utils vs ...
- 2017/2/6:在oracle中varchar与varchar2的区别与增删改查
1.varchar2把所有字符都占两字节处理(一般情况下),varchar只对汉字和全角等字符占两字节,数字,英文字符等都是一个字节:2.VARCHAR2把空串等同于null处理,而varchar仍按 ...
- virtual、abstract、interface区别以及用法
virtual 用于在基类中的使用的方法,使用的情况为: 情况1:在基类中定义了virtual方法,但在派生类中没有重写该虚方法.那么在对派生类实例的调用中,该虚方法使用的是基类定义的方法. ...
- 2019.01.21 bzoj3674: 可持久化并查集加强版(主席树+并查集)
传送门 题意:维护可持久化并查集,支持在某个版本连边,回到某个版本,在某个版本 询问连通性. 思路: 我们用主席树维护并查集fafafa数组,由于要查询历史版本,因此不能够用路径压缩. 可以考虑另外一 ...
- 2018.11.06 bzoj1835: [ZJOI2010]base 基站选址(线段树优化dp)
传送门 二分出每个点不需要付www贡献的范围,然后可以推出转移式子: f[i][j]=f[i−1][k]+value(k+1,j)+c[i]f[i][j]=f[i-1][k]+value(k+1,j) ...
- 6. Uniforms in American's Eyes 美国人眼里的制服
6. Uniforms in American's Eyes 美国人眼里的制服 (1) Americans are proud of their variety and individuality,y ...
- vetur插件提示 [vue-language-server] Elements in iteration expect to have 'v-bind:key' directives
错误如下图所示: 错误提示: [vue-language-server] Elements in iteration expect to have 'v-bind:key' directives.Re ...
- 修改oralce数据库用户名和密码
首先以sys用户登录数据库 一.修改用户名 查到到所需修改用户名称的用户需要:select user#,name from user$;(例如查到有一个normal的用户对应的user#=61) 修改 ...
- Linux主机名域名修改问题
1.修改 /etc/sysconfig/network 配置文件 vi /etc/sysconfig/network 修改HOSTNAMEHOSTNAME=new-hostname.domainn ...