Entity Framework 4.1 Code First (2)

  • 12135
  • 0

Entity Framework 4.1 Code First (2)
簡介Entity 之間1對多,多對多關係

1. 1多對的關係

承接上一篇用到的部門(Department) Entity範例 ,現在增加員工(Employee) Entity

一個員工對應一個部門,一個部門有多個員工

 


	[Table("Employee")]
	public class Employee {
		
		public int EmployeeId { get; set; }

		[Column("EmployeeName")]
		public String Name { get; set; }

		public String Title { get; set; }

		[Timestamp]
		public byte[] Version { get; set; }

		public int DepartmentId { get; set; }
		
		public virtual Department Department { get; set; }

	}

如果有做過產生 Entity Framework POCO 會發現其實觀念語法都相同,例如Dynamic Proxy 處理 lazy load….

而Version property 有設定一個Timestamp attribute,如此一來在做修改Employee,會以EmployeeId(primary key)與Version 為where 的條件

常用於有Concurrency Conflict 考量的資料

 

另外Department 增加ICollection<Employee> property


public virtual ICollection<Employee> Employees { get; set; }

如此一來,Department與Employee 1對多的關係即可操作

 

2.多對多關係

增加一個專案(Project) Entity,一個員工(Employee)可以屬於多個專案,一個專案也包含多個員工,所以2者是多對多的關係


	[Table("Project")]
	public class Project {

		public int ProjectId { get; set; }

		public String ProjectName { get; set; }

		public DateTime CreateDate { get; set; }

		public virtual ICollection<Employee> Employees { get; set; }
	}

Employee class 增加ICollection<Project> property


public virtual ICollection<Project> Projects { get; set; }

再來是設定2者多對多的關係,在DbContext 的 OnModelCreating method 設定


			modelBuilder.Entity<Employee>()
				.HasMany<Project>(e => e.Projects)
				.WithMany(p => p.Employees)
				.Map(
					m => {
						m.MapLeftKey("EmployeeId");
						m.MapRightKey("ProjectId");
						m.ToTable("ProjectEmployee");
					}
				);

在Entity Framework,若是這種多對多的關係在Database 的Table中,若就只記錄2者的key值時,是並不需要額外再產生一個Entity

而是以2者的Assocation對應的Navigators,Code First 也是,但要註明在Database中對應的Table 名稱

 

3.No foreign key

有時Entity 並不需要或不想要有forgien key,例如 增加一個地區(Location) Entity,每一個員工(Employee)對應一地區(Location),一個地區有多的員工

也是一種一對多關係


	public class Location {

		public int LocationId { get; set; }

		public String LocationName { get; set; }

		public virtual ICollection<Employee> Employees { get; set; }
	}

 

 

但Employee entity並不要有LocationID 這個foreign key,而是只要有Location property


public virtual Location Location { get; set; }

此時一樣在DbContext的 OnModelCreating method 設定


			modelBuilder.Entity<Employee>()
				.HasRequired(e => e.Location)
				.WithMany(l => l.Employees)
				.Map(m => {
					m.MapKey("LocationId");
				});

當然在Database的Employee Table中,仍是用LocationId 欄位作為Foreign key
附上範例說明(一樣用ASP.NET MVC )

下次來說明TPT, TPH, TPC