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.

最新文章

  1. IIS 7 php 7.0 部署WE MALL
  2. autolayout的各种坑
  3. win7文件夹图标中多了一把小锁打不开文件夹怎么办?
  4. RAW格式
  5. HDOJ2005第几天
  6. CentOS6.6源码编译升级GCC至4.8.2
  7. hdu2058java
  8. Redis源代码分析-内存数据结构intset
  9. 常用监控SQL
  10. Java中基础类库使用
  11. Spring随笔 - 事务传播行为
  12. APIO2010特别行动队
  13. Flash Media Live Encoder 使用帮助
  14. 在mysql 5.7中,创建表的字段名中包含双引号的时候,执行会报错
  15. docker搭建及使用:centos7.0+docker+flask+nginx
  16. 使用HttpWebRequest请求https链接时,无法访问的问题,设置ServicePointManager.SecurityProtocol安全协议
  17. 正向与反向拓扑排序的区别(hdu 1285 确定比赛名次和hdu 4857 逃生)
  18. mysql同步复制异常的常见操作-传统复制方式
  19. Selenium的使用
  20. post-image.sh hacking

热门文章

  1. linux 和 主机通信的另类方法
  2. vsftpd只能连接不能上传文件问题
  3. sqlserver中如何将mdf文件还原到数据库
  4. vue 开发系列(六) 企业微信整合
  5. TCP/IP协议(4):网络层
  6. 重启服务器后,启动oracle监听报错 The listener supports no services The command completed successfuslly
  7. ubuntu 16.04 安装pgadmin3
  8. cacti+CentOS6.5
  9. c语言结构体链表
  10. linux下运算的几种方法