Torna al Thread

using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MDEF01.Extra.ManyToManyRelationship { // per ulteriori informazioni: http://msdn.microsoft.com/data/jj591620 internal class Program { private static void Main(string[] args) { using (var db = new MyDbContext()) { db.Database.Initialize(false); } Console.WriteLine("Premi invio per terminare l'applicazione..."); Console.ReadLine(); } } public class MyDbContext : DbContext { static MyDbContext() { Database.SetInitializer(new DropCreateDatabaseAlways<MyDbContext>()); } public DbSet<Product> Products { get; set; } public DbSet<Order> Orders { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { // crea automaticamente una tabella chiamata "dbo.ProductOrders" //modelBuilder.Entity<Product>() // .HasMany(t => t.Orders) // .WithMany(t => t.Products); // per specificare il nome della tabella di collegamento //modelBuilder.Entity<Product>() // .HasMany(t => t.Orders) // .WithMany(t => t.Products) // .Map(t => t.ToTable("OrderDetails")); // e specificare anche il nome delle colonne chiave modelBuilder.Entity<Product>() .HasMany(t => t.Orders) .WithMany(t => t.Products) .Map(t => t.ToTable("OrderDetails") .MapLeftKey("ProductId") .MapRightKey("OrderId")); } } public class Product { public int ProductId { get; set; } public string Name { get; set; } // navigation properties public virtual ICollection<Order> Orders { get; set; } public Product() { this.Orders = new List<Order>(); } } public class Order { public int OrderId { get; set; } public DateTime OrderDate { get; set; } public DateTime ShippedDate { get; set; } // navigation properties public virtual ICollection<Product> Products { get; set; } public Order() { this.Products = new List<Product>(); } } }
Copyright © dotNetHell.it 2002-2025
Running on Windows Server 2008 R2 Standard, SQL Server 2012 & ASP.NET 3.5