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的更多相关文章

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

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

  2. 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 ...

  3. 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 ...

  4. 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 ...

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

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

  6. 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 ...

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

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

  8. 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 ...

  9. 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 ...

随机推荐

  1. ajax的基础

    去年也是这个时候,开始学了ajax,也是这个技术领我走上了网页制作的道路,于是这样感觉到手写html比之前的dw拖拖拽拽要有意思得多. 话不多说,下面是一个例子: 这个是ajax显示页面:index. ...

  2. centos上安装jdk

    今天在centos上安装jdk,总结步骤如下:1.先到oracle下载rpm包:jdk-7u80-linux-x64.rpm (下载地址在百度找找)2.把jdk-7u80-linux-x64.rpm上 ...

  3. day08作业---函数

    '''2.写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者.'''#学会了 原来 range(len(iter)) 是 从零到len-1 的数的组合 建新放在 ...

  4. 2019.01.24 bzoj2310: ParkII(轮廓线dp)

    传送门 题意简述:给一个m*n的矩阵,每个格子有权值V(i,j) (可能为负数),要求找一条路径,使得每个点最多经过一次且点权值之和最大. 思路:我们将求回路时的状态定义改进一下. 现在由于求的是路径 ...

  5. Python处理微信利器——itchat

    接触itchat是一个偶然,上知乎刷出一个有意思的文章.于是乎运行源码,调错加上查阅博客,发现itchat大有可为. 知乎链接:https://zhuanlan.zhihu.com/p/2578293 ...

  6. 微信小程序踩坑集合

    1:官方工具:https://mp.weixin.qq.com/debug/w ... tml?t=1476434678461 2:简易教程:https://mp.weixin.qq.com/debu ...

  7. WebLogic 11gR1修改jdk版本

    WebLogic 11gR1默认是支持jdk1.6的 我们可以进入到E:\weblogic\user_projects\domains\base_domain\bin中的修改setDomainEnv. ...

  8. Silverlight4.0正式版(Silverlight4_Tools)离线安装

    1.从微软的网站下载Silverlight4_Tools.exe(或者http://download.csdn.net/detail/taomanman/4522848)2.执行Silverlight ...

  9. ckeditor 实现ctrl+v粘贴图片并上传、word粘贴带图片

    公司做的项目需要用到文本上传功能. Chrome+IE默认支持粘贴剪切板中的图片,但是我要粘贴的文章存在word里面,图片多达数十张,我总不能一张一张复制吧? 我希望打开文档doc直接复制粘贴到富文本 ...

  10. AIX 批量更改密码

    使用 chpasswd 可以使用 chpasswd 方便地更改单个或多个账户密码.这意味着不需要像平时一样在命令行上重复输入密码.尽管可以以交互方式使用 chpasswd,但是我建议以非交互方式使用它 ...