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 ...
随机推荐
- php与html代码的若干转换
以前懵懵懂懂的看过,没怎么在意,现在总结一下 一般来说,像留言板之类的content,用这样的就够了: $content=addslashes(htmlspecialchars($_POST['con ...
- 【Linux】percona-toolkit工具包的安装
一.检查和安装与Perl相关的模块 PT工具是使用Perl语言编写和执行的,所以需要系统中有Perl环境. 依赖包检查命令为: rpm -qa perl-DBI perl-DBD-MySQL perl ...
- POJ-3252 Avenger
题意:在区间中,他们化成2进制的数的0的个数大于等于1的数有多少个. 思路:我们需要记录上一次0和1的个数,此外我们还要特别注意一下前导0. 如果前面全是0的时候我们就要注意下一位是不是还是0,如果一 ...
- 如何将字符串转化为Jsoup的Document 对象
有些时候在java操作解析html元素的时候比较繁琐,今天螃蟹就介绍一种可将html转换为document对象的方法——jsoup jsoup为我们解析html提供了比较全的API接口,我们通过将ht ...
- 2019.01.03 bzoj3456: 城市规划(生成函数+多项式取对)
传送门 生成函数好题. 题意:求n个点的简单(无重边无自环)无向连通图数目 思路: 对简单无向图构造生成函数f(x)=∑n2Cn2xnn!f(x)=\sum_n2^{C_n^2}\frac{x^n}{ ...
- 2018.10.27 loj#6035. 「雅礼集训 2017 Day4」洗衣服(贪心+堆)
传送门 显然的贪心题啊...考试没调出来10pts滚了妙的一啊 直接分别用堆贪心出洗完第iii件衣服需要的最少时间和晾完第iii件衣服需要的最少时间. 我们设第一个算出来的数组是aaa,第二个是bbb ...
- 设置vue启动项目后默认显示的页面
通过配置路由,可以设置vue项目启动后默认显示的页面.路由的path设置为path:"/",启动项目后就会显示默认的组件页面. import Vue from 'vue' impo ...
- 详细介绍jQuery.outerWidth() 函数具体用法
outerWidth()函数用于设置或返回当前匹配元素的外宽度.外宽度默认包括元素的内边距(padding).边框(border),但不包括外边距(margin)部分的宽度.你也可以指定参数为true ...
- Keras人工神经网络多分类(SGD)
import numpy as np import pandas as pd from keras.models import Sequential from keras.layers import ...
- revoke回收权限的小问题
revoke回收权限的时候,原理是从user/db/tables_priv/columns_priv四个表上delete数据: on *.*的权限在user表上 on xx.*的权限在db表上 on ...