Created
February 12, 2016 20:11
-
-
Save morecchia/f24b8fd1713c43eea86e to your computer and use it in GitHub Desktop.
Set up an Entity Framework database with one-to-many relationships using Code First
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using MyProject.Models; | |
using System.Data.Entity; | |
using System.Data.Entity.ModelConfiguration.Conventions; | |
namespace MyProject.Database | |
{ | |
public class ArchiveDatabase : DbContext | |
{ | |
// add a connection string in Web.config | |
// <add name="MyConnection" connectionString="Server=localhost;Database=MyDatabase;Trusted_Connection=true;" providerName="System.Data.SQLClient" /> | |
public MyDatabase() : base("MyConnection") { } | |
public DbSet<Case> Cases { get; set; } | |
public DbSet<Client> Clients { get; set; } | |
public DbSet<Matter> Matters { get; set; } | |
protected override void OnModelCreating(DbModelBuilder modelBuilder) | |
{ | |
// add one-to-many relationships | |
modelBuilder.Entity<Client>().HasMany(cl => cl.Matters); | |
modelBuilder.Entity<Matter>().HasMany(m => m.Cases); | |
// remove cascading delete restriction | |
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); | |
base.OnModelCreating(modelBuilder); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment