Home > Enterprise >  How to use ForeignKey
How to use ForeignKey

Time:04-07

I am currently doing an API with ASP.NET Core and EntityFrameworkCore.

The objective of this API is to manage indemnity bulletins. An indemnity bulletin contains a list of activities carried out during the month.

For storage, I use an SQL server and I made the choice to make two tables:

  • A table for the information of an indemnity bulletin (Name, First name, Month/Year)
  • A table for the contents of the indemnity bulletin (Start and end of activity time, activity name and ID of the indemnity bulletin containing this line)

So I have two objects:

public class PaySlip
{
    [Key]
    public int Id { get; set; }
 
    [Required]
    public string Month { get; set; }
 
    [ForeignKey(nameof(PaySlipLine.Id))]
    public ICollection<PaySlipLine> PaySlipLines { get; set; }
}
public class PaySlipLine
{
    [Key]
    public int Id { get; set; }
 
    public DateTime StartDateTime { get; set; }
 
    public DateTime EndDateTime { get; set; }
 
    [ForeignKey(nameof(PaySlip.Id))]
    public int PaySlipId { get; set; }
}

So here’s my problem, the database creates two tables. In my API, I can send a PaySlip with PaySlipLines. Except that when I recover them, they do not contain PaySlipLines :(

However, the PaySlipLines are well contained in the DB with the right ID

I tried to:

  • [ForeignKey(nameof(PaySlipLine.Id))] by [ForeignKey(nameof(PaySlipLine.PaySlipId))] in the PaySlip class
  • Initialize the PaySlip collection with a List

CodePudding user response:

Except that when I recover them, they do not contain PaySlipLines :(

Use Include, like so:


List<PaySlip> paySlips = await yourDbContext.PaySlips
    .Include( p => p.PaySlipLines )
    .OrderBy( p => p.Month )
    .ToListAsync()
    .ConfigureAwait(false);

foreach( PaySlip ps in paySlips )
{
    Console.WriteLine( "PaySlip: {0} {1}", ps.Id, ps.Month );

    foreach( PaySlipLine l in ps.PaySlipLines )
    {
        Console.WriteLine( "\t{0:d} to {1:d}:", l.StartDateTime, l.EndDateTime );

    }
    Console.WriteLine();
}

Also, you probably shouldn't be storing dates as String Month.

  • Related