我認爲這就是它,1:0..1。僱員可具有EmployeeOptions,一個EmployeeOptions必須有一個員工,和Employee表由遷移原封不動:
public class Employee
{
[Key]
public int EmpId { get; set; }
public string FName { get; set; }
public string LName { get; set; }
[ForeignKey("EmpId")]
public virtual EmployeeOption EmployeeOption { get; set; }
}
public class EmployeeOption
{
[Key]
public int EmpId { get; set; }
public string Option1 { get; set; }
public string Option2 { get; set; }
[ForeignKey("EmpId")]
public virtual Employee Employee { get; set; }
}
public class ExampleContext : DbContext
{
public ExampleContext() : base("DefaultConnection") { this.Configuration.ProxyCreationEnabled = false; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>()
.HasOptional(o => o.EmployeeOption)
.WithOptionalPrincipal(e => e.Employee);
}
public DbSet<Employee> Employees { get; set; }
public DbSet<EmployeeOption> EmployeeOptions { get; set; }
}
生成表(遷移):
CreateTable(
"dbo.EmployeeOptions",
c => new
{
EmpId = c.Int(nullable: false),
Option1 = c.String(),
Option2 = c.String(),
})
.PrimaryKey(t => t.EmpId)
.ForeignKey("dbo.Employees", t => t.EmpId)
.Index(t => t.EmpId);
CreateTable(
"dbo.Employees",
c => new
{
EmpId = c.Int(nullable: false, identity: true),
FName = c.String(),
LName = c.String(),
})
.PrimaryKey(t => t.EmpId);
編輯:通過使用下面的流利的映射,而不是上面的一個你可以刪除[ForeignKey]屬性:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<EmployeeOption>()
.HasRequired(e => e.Employee)
.WithOptional(e => e.EmployeeOption);
}
嘗試'WithRequired'而不是'WithOptionalPrincipal'。 –