Database Reference
In-Depth Information
// assign the foreign key directly
invoice2.ClientId = 1;
// Attach() an existing row using a "fake" entity
context.Database.ExecuteSqlCommand("insert into chapter5.client values (2, 'Phil Marlowe')");
var client2 = new Client { ClientId = 2 };
context.Clients.Attach(client2);
invoice3.Client = client2;
// using the ClientReference
invoice4.Client = client1;
// save the changes
context.Clients.Add(client1);
context.Invoices.Add(invoice2);
context.Invoices.Add(invoice3);
context.Invoices.Add(invoice4);
context.SaveChanges();
}
using (var context = new EFRecipesEntities())
{
foreach (var client in context.Clients)
{
Console.WriteLine("Client: {0}", client.Name);
foreach (var invoice in client.Invoices)
{
Console.WriteLine("\t{0} for {1}", invoice.InvoiceDate.ToShortDateString(),
invoice.Amount.ToString("C"));
}
}
}
The following is the output of the code in Listing 5-37:
Client: Karen Standfield
4/1/2010 for $29.95
4/4/2010 for $45.99
4/2/2010 for $49.95
Client: Phil Marlowe
4/3/2010 for $102.95
How It Works
Entity Framework supports independent associations and foreign key associations. For an independent association,
the association between the entities is tracked separately from the entities, and the only way to change the association
is through object references.
 
Search WWH ::




Custom Search