我正在尝试配置一个可选的必需简单关系,但EF似乎没有支持正确的迁移:
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 :(得分: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; }
如果Id字段是int,则会自动获取。