Frame code entity

I am using fluent api for the first time. I can establish relationships by using relationships from one to many, many to many.

But I have an explanation using a one-to-one relationship.

I have two tables tableA and tableB, where tableA has two fields

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

And tableB has the following fields:

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

}

I define constraints in a separate class, for example:

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);
}
}

How to determine the foreign key relationship in the above class in the first code approach?

+4
source share
2 answers

Define your free api configuration class as follows:

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

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

, refKeyfromTableA tableB , - . , 2 , tAId tBId . , , , . , tableB :

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

WithRequired, WithOptionalDependent WithOptionalPrincipal " ", .

+3

1:1 API, . , , , , :

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; }
}
0

Source: https://habr.com/ru/post/1622946/


All Articles