-
Notifications
You must be signed in to change notification settings - Fork 0
OneToMany
Marcin Sulecki edited this page Apr 4, 2017
·
10 revisions
Model
public class Department
{
public int DepartmentID { get; set; }
public string Name { get; set; }
public ICollection<Employee> Employees { get; set; }
}
public class Employee
{
public int EmployeeID { get; set; }
public string Name { get; set; }
public Department Department { get; set; }
}
Na podstawie konwencji powstanie pole null o nazwie Department_DepartmentId
Model
public class Department
{
public int DepartmentID { get; set; }
public string Name { get; set; }
public ICollection<Employee> Employees { get; set; }
}
public class Employee
{
public int EmployeeID { get; set; }
public string Name { get; set; }
public int DepartmentId { get; set; }
public Department Department { get; set; }
}
Na podstawie konwencji powstanie kolumna not null o nazwie DepartmentId
Jeśli chcemy, aby kolumna DepartmentId była not null to pole musi być typu Nullable:
public int? DepartmentID { get;set;}
Model
public class Department
{
public int DepartmentID { get; set; }
public string Name { get; set; }
public ICollection<Employee> Employees { get; set; }
}
public class Employee
{
public int EmployeeID { get; set; }
public string Name { get; set; }
public Department Department { get; set; }
}
Konfiguracja:
modelBuilder.Entity<Employee>()
.HasRequired(e => e.Department)
.WithMany(d => d.Employees);
Na podstawie konfiguracji powstanie pole not null o nazwie Department_DepartmentId
Jeśli chcemy, aby kolumna Department_DepartmentId była null to możemy to zmienić za pomocą metody HasOptional.
modelBuilder.Entity<Employee>()
.HasOptional(e => e.Department)
.WithMany(d => d.Employees);
Jeśli chcemy dodać pole klucza obcego to musimy w konfiguracji wskazać to pole za pomocą metody HasForeignKey
Model
public class Employee
{
public int EmployeeID { get; set; }
public string Name { get; set; }
public int? DepartmentId { get; set; }
public Department Department { get; set; }
}
Konfiguracja
modelBuilder.Entity<Employee>()
.HasOptional(e => e.Department)
.WithMany(d => d.Employees)
.HasForeignKey(e => e.DepartmentId);