【问题标题】:EF Fluent API One-to-One relationshipEF Fluent API 一对一关系
【发布时间】:2013-05-05 06:27:31
【问题描述】:

我正在尝试配置可选必需的简单关系,但 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 不是作为外键生成并且可以为空,因为它是关系的可选部分?

【问题讨论】:

    标签: entity-framework entity-framework-4 entity-framework-5


    【解决方案1】:

    在你的领域类中尝试

    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,则应自动获取。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-04
      • 2020-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-27
      • 2019-05-27
      • 1970-01-01
      相关资源
      最近更新 更多