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. 图解http学习笔记【一】

    不想单纯的把书里的知识点罗列一遍 这周,我们的安全代码终于改完了.我在微信上报了个叫 一修读书的课程,现在已经听了6天.感觉并不是很神奇,聊胜于无.倒是趁着当当搞活动买回来好几本书,其中就有这本图解h ...

  2. dedecms首页搜索 添加仿百度下拉框

    1:找到uploads/templets/default/head.htm 2: 找到 <input name="q" type="text"  clas ...

  3. ubuntu下使用fstab挂载硬盘时,属于root,如何把它改为属于一个用户的(如sgjm)

    http://zhidao.baidu.com/link?url=xnakfVD16EtunTSt3wBm153DyqHnXN3FSPO1E_2SpVmM5bmEIwICLA0N6zN85_ioQ3f ...

  4. linux_域名映射

    vi /etc/hosts在最后加上ip及映射的域名 192.168.229.111 node001 192.168.229.112 node002 192.168.229.113 node003

  5. 31、iOS 正则表达式判断UITextField是否为全汉字,全字母,全数字,数字和字母

    判断全汉字 if ([self deptNameInputShouldChinese]) { [DemonAlertHelper showToastWithMessage:@"只能是中文&q ...

  6. 【转】linux 磁盘挂载

    挂载好新硬盘后输入fdisk -l命令看当前磁盘信息 可以看到除了当前的第一块硬盘外还有一块sdb的第二块硬盘,然后用fdisk /dev/sdb 进行分区 进入fdisk命令,输入h可以看到该命令的 ...

  7. Oracle服务器修改IP后

    机房有两套网络,一套办公网,一套机房的内网,办公网可以通过vpn在其他地方访问,内网只能在公司办公室访问.团队有同事去外地办公,开发的时候需要通过客户端直连数据库,于是把数据库服务器的网线换到办公网的 ...

  8. react添加方法的两种形式

    1.使用bind <button onClick={this.test.bind(this)}>确定</button> 2.使用箭头函数 <button onClick= ...

  9. 2.Early Education of Children 儿童的早期教育

    2.Early Education of Children 儿童的早期教育 (1) In bringing up children,every parent watches eagerly the c ...

  10. IE上如何设置input type=file的光标不闪烁

    我们使用文件上传时,时常自定义图标,这时候通常会把input的透明度设置为0,但是在IE上使用时会出现光标闪烁问题 解决办法 css设置font-size为0