0

我想配置可选要求的简单关系,而是EF似乎并不脚手架正确迁移:EF流利的API一比一的关系

public class Applicant 
{ 
    public int Id { get; set; } 

    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public int ContactInfoId   { get; set; } 
    public string PreferredCultureId { get; set; } 

    public virtual ApplicantContact  Contact    { get; set; } 
    public virtual Culture    PreferredCulture { get; set; } 
} 




public ApplicantConfiguration() 
{ 
    HasKey(a => a.Id); 
    Property(a => a.FirstName).IsRequired().HasMaxLength(50); 
    Property(a => a.LastName).IsRequired().HasMaxLength(50); 

    HasOptional(a => a.Contact) 
     .WithRequired(c => c.Applicant) 
     .WillCascadeOnDelete(); 

    HasOptional(a => a.PreferredCulture) 
     .WithMany() 
     .HasForeignKey(a => a.PreferredCultureId); 
} 






CreateTable(
    "Main.Applicants", 
    c => new 
     { 
      Id = c.Int(nullable: false, identity: true), 
      FirstName = c.String(nullable: false, maxLength: 50), 
      LastName = c.String(nullable: false, maxLength: 50), 
      ContactInfoId = c.Int(nullable: false), 
      PreferredCultureId = c.String(maxLength: 128), 
     }) 
    .PrimaryKey(t => t.Id) 
    .ForeignKey("General._Cultures", t => t.PreferredCultureId) 
    .Index(t => t.PreferredCultureId); 

为什么ContactInfoId没有被生成为外键并且可以为空,因为它是关系的可选方面?

回答

0

在你的领域类尝试

public class Applicant 
{ 

    public string FirstName { get; set; } 
    public string LastName { get; set; } 

    public virtual ApplicantContact  Contact    { get; set; } 
    public virtual Culture    PreferredCulture { get; set; } 
} 


public class ContactInfo 
{ 
    // whatever contact info fields you have 
} 

public class Culture 
{ 
    // culture fields 
} 

然后在上下文中有

public DbSet<ContactInfo> ContactInfos { get; set; } 
public DbSet<Applicant> Applicants { get; set; } 
public DbSet<Culture> Cultures { get; set; } 

,如果他们是INT ID字段应该自动获得。