博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Lerning Entity Framework 6 ------ Defining Relationships
阅读量:7112 次
发布时间:2019-06-28

本文共 5106 字,大约阅读时间需要 17 分钟。


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
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
Companies { get; set; } public DbSet
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:

图片.png-4.2kB

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
() { 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:

图片.png-1.3kB

图片.png-1.8kB

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
{ 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
Employees { get; set; }}class Person{ public int PersonId { get; set; } [MaxLength(50)] public string PersonName { get; set; } public virtual ICollection
companies { get; set; }}class MyContext:DbContext{ public MyContext():base("name=Test") { } public DbSet
Companies { get; set; } public DbSet
People { get; set; }}

After execute the command Upate-Database, take a look at the database:

图片.png-2.8kB

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
{ 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 DbContextprotected 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
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
{ 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: .

That's all.

转载于:https://www.cnblogs.com/zzy0471/p/6839220.html

你可能感兴趣的文章
C++string与VC++CString互转
查看>>
迈出第一步
查看>>
GOROOT与GOPATH
查看>>
十二周三次课 (3月14日)
查看>>
JavaScript权威设计--jQuery,Ajax.animate,SVG(简要学习笔记二十)[完结篇]
查看>>
[原]iBatis.Net(C#)系列一:简介及运行环境
查看>>
读/写锁的实现和应用(高并发状态下的map实现)
查看>>
ReportingService 通过RowNumber函数获取行号和生成隔行变色样式
查看>>
lpxelinux启动linux
查看>>
2014/08/23——OJ出现waiting...
查看>>
Perl 5 教程
查看>>
JobTracker作业启动过程分析
查看>>
lucene、lucene.NET详细使用与优化详解
查看>>
微机原理(1)
查看>>
Codeforces Educational Codeforces Round 3 E. Minimum spanning tree for each edge LCA链上最大值
查看>>
数据结构之计算器的实现(JAVA)(四)
查看>>
基于http协议的api接口对于客户端的身份认证方式以及安全措施
查看>>
Oracle基础(五)pl/sql进阶(分页过程)
查看>>
Deep Introduction to Go Interfaces.
查看>>
SVG的内部事件添加
查看>>