Database Reference
In-Depth Information
[Table("WorkerTask", Schema = "Chapter6")]
public class WorkerTask
{
[Key]
[Column(Order = 1)]
public int WorkerId { get; set; }
[Key]
[Column(Order = 2)]
public int TaskId { get; set; }
[ForeignKey("WorkerId")]
public virtual Worker Worker { get; set; }
[ForeignKey("TaskId")]
public virtual Task Task { get; set; }
}
How It Works
During the application development lifecycle, developers often find the need to add payload to the many-to-many
associations that started life payload-free. In this recipe, we show how to surface the many-to-many association as a
separate entity so that additional scalar properties (for example, payload) can be added.
Many developers choose to assume that all many-to-many relationships will ultimately hold a payload, and they
create a synthetic key for the link table rather than the traditional composite key formed by combining the foreign keys.
The downside of our new model is that we do not have a simple way to navigate the many-to-many association.
We have two one-to-many associations that require an additional hop through the linking entity. The code in
Listing 6-3 demonstrates this additional bit of work on both the insert side and the query side.
Listing 6-3. Inserting into and Retrieving Task and Worker Entities
using (var context = new EF6RecipesContext())
{
var worker = new Worker { Name = "Jim" };
var task = new Task { Title = "Fold Envelopes" };
var workertask = new WorkerTask { Task = task, Worker = worker };
context.WorkerTasks.Add(workertask);
task = new Task { Title = "Mail Letters" };
workertask = new WorkerTask { Task = task, Worker = worker };
context.WorkerTasks.Add(workertask);
worker = new Worker { Name = "Sara" };
task = new Task { Title = "Buy Envelopes" };
workertask = new WorkerTask { Task = task, Worker = worker };
context.WorkerTasks.Add(workertask);
context.SaveChanges();
}
using (var context = new EF6RecipesContext())
{
Console.WriteLine("Workers and Their Tasks");
Console.WriteLine("=======================");
 
Search WWH ::




Custom Search