实体框架代码第一流畅的api

时间:2016-01-05 16:34:42

标签: c# .net entity-framework entity-framework-6 ef-fluent-api

我第一次使用流畅的api。我能够利用一对多和多对多的关系来建立关系。

但我使用一对一的关系进行澄清。

我有两个表tableA和tableB,其中tableA有两个字段

public class tableA
{
 public int tAId {get;set;}
 public string desc {get;set;}
 public tableB tableB {get;set;}
}

tableB有以下字段:

public class tableB
{
  public int tBId {get;set;}
  public int refKeyfromTableA{get;set;}
  public string somedesc{get;set;}
  public tableA tableA {get;set;}

}

我在一个单独的类中定义约束,如:

public class tableAConfig:BaseEntity<tableA>
{
public tableAConfig()
{
  HasKey(p=>p.tAId);
Property(p=>p.tAId).IsRequired();

//This line has syntatical error
HasForeignKey(p=>p.tAId);
}
}

如何在代码优先方法中定义上述类中的外键关系?

2 个答案:

答案 0 :(得分:3)

定义您的流畅api配置类,如下所示:

public class tableAConfig:BaseEntity<tableA>
{
    public tableAConfig()
    {
        HasKey(p=>p.tAId);

        HasOptional(p => p.tableB )
            .WithRequired( p => p.tableA );
    }
}

考虑到tableB实体上的属性refKeyfromTableA是无用的,因为主键之间形成了数据库中的一对一关系。因此,在您的情况下,如果他们的tAId和tBId列具有相同的值,则2个实体是相关的。因此,至少一个实体的主键值不能由数据库生成。例如,在tableB的配置中,您可以按如下方式执行:

Property(e => e.tBId)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

除了WithRequired方法,你也可以使用WithOptionalDependent和WithOptionalPrincipal方法来形成一对一的关系。

答案 1 :(得分:0)

我还没有使用流畅的API 1:1,但我已经使用属性完成了它。我修复了一个代码示例,演示了属性方法以与您的示例保持一致,也许它会对您有所帮助:

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

    public string desc { get; set; }

    public tableB tableB { get; set; }
}

public class tableB
{
    // In one-to-one relationship, one end must be principal and second end must be dependent. 
    // tableA is the one which will be inserted first and which can exist without the dependent one. 
    // tableB end is the one which must be inserted after the principal because it has foreign key to the principal.

    [Key, ForeignKey("tableA")]
    public int Id { get; set; }

    // 'Required' attribute because tableA must be present
    // in order for a tableB to exist
    [Required]
    public virtual tableA tableA { get; set; }

    public string somedesc { get; set; }
}
相关问题