I'm new to Entity Framework and I am trying to configure two navigation properties in a Code-First project.
The first property is a collection of employee_pay_period(s). Each employee_salary has multiple employee_pay_period(s) and each employee_pay_period has one employee_salary.
employee_pay_period.employee_salary_id is a foreign key.
The second property, employee_salary.employee_current_pay_period, is a bit more tricky. It is a property that points to the current employee_pay_period. So a navigation property going from one employee_salary to one employee_pay_period. There is NO foreign key in the DB associated with the second property and each employee_salary MUST contain an employee_current_pay_period.
How do I use fluent API to map these properties correctly.
public class employee_salary
{
public employee_salary()
{
employee_pay_period = new HashSet<employee_pay_period>();
}
[Key]
public int employee_salary_id { get; set; }
public int? employee_current_pay_period_id { get; set; }
public virtual employee_pay_period employee_current_pay_period { get; set; }
public virtual ICollection<employee_pay_period> employee_pay_period { get; set; }
}
public partial class employee_pay_period
{
[Key]
public int employee_pay_period_id { get; set; }
public int employee_salary_id { get; set; }
public virtual employee_salary employee_salary { get; set; }
}
If I understand correctly you want a 1-many relationship between employee_salary
and employee_pay_period
respectively but also a 1-1 relationship between an employee_salary
and the current employee_pay_period
So something like this (assuming you already have the rest of the fluentApi context configuration class set up) in the OnModelCreating(ModelBuilder builder)
function:
builder.Entity<employee_salary>(e =>
{
e.HasMany(s => s.employee_pay_period) // salary has many pay periods
.WithOne(p => p.employee_salary) // pay period has one salary
.HasForeignKey(p => p.employee_salary_id) // foreign key on pay period linking to a single salary id
.OnDelete(DeleteBehavior.Restrict); // Or whatever the desired delete behaviour should be
e.HasOne(s => s.employee_current_pay_period) // salary has one current pay period
.WithOne(p => p.employee_salary) // pay period has one salary
.HasForeignKey<employee_salary>(s => s.employee_current_pay_period_id) // foreign key on salary linking to a single current pay period id
.OnDelete(DeleteBehavior.Restrict); // Or whatever the desired delete behaviour should be
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.