How to create relationships in EF Core from an entity model

0

how can I create relationships with EF code

Client - > Customer registration PersonalInformation - > Personal information of the client Payment History - > Condo payment reports

public class Client{
    [Key]
    public int Id { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
}
public class PersonalInformation{
    [Key]
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Phone { get; set; }
    public string CellPhone { get; set; }
}
public class PaymentHistory{
    [Key]
    public int Id { get; set; }
    public string PayNumber { get; set; }
    public double CurrentBalance { get; set; }
    public double CreditBalance { get; set; }
}
    
asked by Maria Perez 07.05.2018 в 20:54
source

1 answer

0

The easiest way is to relate them to your database manager and then when you generate them with Scaffold-DbContext you will automatically generate the relationships, but you must have the foreign keys defined.

If you are going to create your models from the project (CodeFirst) then you can manually add the properties to them to relate them.

Example

If you want to relate Client and PaymentHistory it would be this way

 public class Client{
        [Key]
        public int Id { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public ICollection<PaymentHistory> PaymentHistories { get;set;}
    }

    public class PaymentHistory{
        [Key]
        public int Id { get; set; }
        public string PayNumber { get; set; }
        public double CurrentBalance { get; set; }
        public double CreditBalance { get; set; }
        public int ClientId { get; set; }
        public Client Client { get; set; }
    }

Then in the context you set up the relationship using fluent api

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
 modelBuilder.Entity<PaymentHistory>()
            .HasOne(p => p.Client)
            .WithMany(c =>c.PaymentHistories)
            .HasForeignKey(p => p.ClientId);
}

Here is the official documentation that explains the different ways to relate entities .

Then if you want to get the list of clients with your payment history, you do it this way

var clientesConPagos=context.Client.include(p=>p.PaymentHistories).ToList();
    
answered by 07.05.2018 в 22:10