I have a requirement whereby I need to link 2 entities in the database (using Code First generation) but I'm a little unsure how to define the foreign keys/relationship so I can access each item from the other.
Basically, a Job can exist without any requirement for a Ticket. A Ticket can also exist without a Job, but ultimately a Job will be created for an existing Ticket.
I'm using Entity Framework 6
public class Job
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid JobId { get; set; }
//Other Properties
public virtual Ticket Ticket { get; set; }
}
public class Ticket
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid TicketId { get; set; }
//Other Properties
public virtual Job Job { get; set; }
}
Then, essentially what I want to be able to do is select a Job with it's Ticket (if it has one) and a Ticket with it's Job (if it has one).
i.e.
var tickets = context.Tickets
.Include(ticket => ticket.Job);
and
var job = context.Jobs
.Include(job => job.Ticket);
Do I put a nullable Foreign Key on both Tables?
public class Job
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid JobId { get; set; }
//Other Properties
public Guid? TicketId { get; set; )
[ForeignKey("TicketId")]
public virtual Ticket Ticket { get; set; }
}
public class Ticket
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid TicketId { get; set; }
//Other Properties
public Guid? JobId { get; set; )
[ForeignKey("JobId ")]
public virtual Job Job { get; set; }
}
...or is there a better way to do this (ideally using Data Annotations)?
Thanks in advance for any guidance offered.
Edit: The following seems to work but of course doesn't guarantee a Unique Key on Job for TicketId and on TicketId for JobId: - Correction: This doesn't work for retrieving the Foreign Key properties - see below
public class Job
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid JobId { get; set; }
//Other Properties
[InverseProperty("Jobs")]
public Guid? TicketId { get; set; )
[ForeignKey("TicketId")]
public virtual ICollection<Ticket> Tickets { get; set; }
}
public class Ticket
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid TicketId { get; set; }
//Other Properties
[InverseProperty("Tickets")]
public Guid? JobId { get; set; )
[ForeignKey("JobId ")]
public virtual ICollection<Job> Jobs { get; set; }
}
EDIT: See Serge answer for .NET Core. I've tried the above and that doesn't retrieve the Child properties for each Entity. I.e. no Ticket when retrieving Jobs and no Job when retrieving Tickets.
Still stuck if anyone has any ideas!