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
The One-to-Many relationship
Write some codes first:
class Company
{
public int CompanyId { get; set; }
[MaxLength(50)]
public string CompanyName { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
class Employee
{
public int EmployeeId { get; set; }
[MaxLength(50)]
public string EmployeeName { get; set; }
public virtual int CompanyId { get; set; }
}
class MyContext:DbContext
{
public MyContext():base("name=Test")
{
}
public DbSet<Company> Companies { get; set; }
public DbSet<Employee> Employees { get; set; }
}
We use the virtual keyword when define the navigation property. This keyword can enable us to use lazy loading. It' means Entity Framework will load the data to Employees property of Company automatic only when we attempt to access it.
After execute command Update-Database in Nuget command line, take a look at database:

The column Companyid is created as the foreign key automatic.
Let's have a test:
static void Main(string[] args)
{
Company company1 = new Company
{
CompanyName = "Baidu",
Employees = new List<Employee>()
{
new Employee
{
EmployeeName = "Joey",
},
new Employee
{
EmployeeName = "Ross",
}
}
};
AddCompany(company1);
}
private static void AddCompany(Company company)
{
using (MyContext db = new MyContext())
{
db.Companies.Add(company);
db.SaveChanges();
}
}
After Run the program, there have been some data:


Now, Let's try to delete the company:
static void Main(string[] args)
{
DeleteCompany(1);
}
private static void DeleteCompany(int companyId)
{
using (MyContext db = new MyContext())
{
Company company = db.Companies.Find(companyId);
if (company != null)
{
db.Companies.Remove(company);
db.SaveChanges();
}
}
}
After run the program, you'll find the employee data is deleted also. Cascade deletion is the default way. if you don't want Cascade deletion, you can configurate it by The DbModelBuilder API or Configuration Classes:
class CompanyMap : EntityTypeConfiguration<Company>
{
public CompanyMap()
{
HasMany(c => c.Employees)
.WithRequired()
.HasForeignKey(c=>c.CompanyId)
.WillCascadeOnDelete(false);
}
}
If you don't need to access proerty CompanyId in class Employee, you'd better remove it from the class Employee. Then Entity Framework will create a foreign key named Company_CompanyId automatic. Of cause, you can define it flexible by using The DbModelBuilder API or Configuration Classes.
The Many-to-Many relationship
Write some codes first:
class Company
{
public int CompanyId { get; set; }
[MaxLength(50)]
public string CompanyName { get; set; }
public virtual ICollection<Person> Employees { get; set; }
}
class Person
{
public int PersonId { get; set; }
[MaxLength(50)]
public string PersonName { get; set; }
public virtual ICollection<Company> companies { get; set; }
}
class MyContext:DbContext
{
public MyContext():base("name=Test")
{
}
public DbSet<Company> Companies { get; set; }
public DbSet<Person> People { get; set; }
}
After execute the command Upate-Database, take a look at the database:

Entity Framework has created a junction table named personcompanies. it's contains two columns: personId and companyId.
Of cause, you also can define the columns's name by coding, for example:
class PersonMap:EntityTypeConfiguration<Person>
{
public PersonMap()
{
HasMany(p => p.companies)
.WithMany(c => c.Employees)
.Map(m =>
{
m.MapLeftKey("PersonId");
m.MapRightKey("CompanyId");
});
}
}
Add it to Configurations of modelBuilder:
// OnModelCreating is a fucntion of DbContext
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new PersonMap());
}
The One-to-One relationship
Coding first:
class Person
{
public int PersonId { get; set; }
[MaxLength(50)]
public string PersonName { get; set; }
public virtual ICollection<Company> companies { get; set; }
public virtual Student Student{ get; set; }
}
class Student
{
[Key]
public int PersonId { get; set; }
[MaxLength(200)]
public string SchoolName { get; set; }
public virtual Person Person { get; set; }
}
class StudentMap:EntityTypeConfiguration<Student>
{
public StudentMap()
{
HasRequired(s => s.Person)
.WithOptional(s => s.Student);
}
}
A student must be a person, but a person dosn't must be student, so, the codes like this:
HasRequired(s => s.Person).WithOptional(s => s.Student);
There is another way to create One-to-One relationship. Please see: Lerning Entity Framework 6 ------ Introduction to TPT.
That's all.
Lerning Entity Framework 6 ------ Defining Relationships的更多相关文章
- 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 ------ 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 ------ Inserting, Querying, Updating, and Deleting Data
Creating Entities First of all, Let's create some entities to have a test. Create a project Add foll ...
- Lerning Entity Framework 6 ------ Introduction to TPH
Sometimes, you have created two models. They have the same parent class like this: public class Pers ...
- 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 ...
- Lerning Entity Framework 6 ------ A demo of using Entity framework with MySql
Create a new project named MySqlTest Install following packages by right-clicking on the References ...
- Lerning Entity Framework 6 ------ Joins and Left outer Joins
Joins allow developers to combine data from multiple tables into a sigle query. Let's have a look at ...
随机推荐
- JDK8集合类源码解析 - ArrayList
ArrayList主要要注意以下几点: 1构造方法 2添加add(E e) 3 获取 get(int index) 4 删除 remove(int index) , remove(Objec ...
- Android中fragment之间和Activity的传值、切换
功能介绍:通过一个activity下方的三个按钮,分别是发送消息(sendButton).聊天记录(chatButton).常用语(commonButton).当单击按钮是,来切换上方的fragmen ...
- 社区发现(Community Detection)算法(转)
作者: peghoty 出处: http://blog.csdn.net/peghoty/article/details/9286905 社区发现(Community Detection)算法用来发现 ...
- 2019.01.19 洛谷P2787 语文1(chin1)- 理理思维(ODT)
传送门 ODTODTODT水题. 题意:有一个字母序列,支持区间赋值,查询区间某个字母的数量,区间按字母序排序. 思路: 可以开262626棵线段树搞过去,然而也可以用ODTODTODT秒掉. 如果用 ...
- 2019.01.13 loj#6515. 贪玩蓝月(线段树分治+01背包)
传送门 题意简述:有一个初始为空的双端队列,每次可以在队首和队尾插入或弹出一个二元组(wi,vi)(w_i,v_i)(wi,vi),支持询问从当前队列中选取若干个元素是的他们的和对 MODMODM ...
- 哪些优秀的 Windows 小工具,类似 clover 或 everything
有哪些优秀的 Windows 小工具,类似 clover 或 everything? 目前已知的有everything, listary, total commander, clover, dexpo ...
- C语言的问题,头文件:keil也许有漏洞
2018-06-15 16:52:03 ------------------------------------------------------------------------------ ...
- eclipse 创建servlet 出现继承 HttpServlet 报红线
eclipse创建servlet出现红线: 解决方案1,鼠标右键项目 -> 鼠标右击项目——>Build Path——> 点击comfigure Build Path进入-----& ...
- 关于css中设置属性的常识
1.cellspacing 属性规定单元格之间的空间,请勿将该属性与 cellpadding 属性相混淆. 2.cellpadding 属性规定的是单元边沿与单元内容之间的空间. 3.text-ali ...
- js 上传文件夹
最近公司做工程项目,实现文件夹上传. 网上找了一天,发现网上很多代码都存在相似问题,最后终于找到了一个符合要求的项目. 工程如下: 这里对项目的文件传输功能做出分析,怎么实现文件夹上传的,如何进行文件 ...