Skip to content

Instantly share code, notes, and snippets.

@sphingu
Created February 26, 2014 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sphingu/092f68edc74cc446c9e4 to your computer and use it in GitHub Desktop.
Save sphingu/092f68edc74cc446c9e4 to your computer and use it in GitHub Desktop.
public class LibraryContext : DbContext
{
public LibraryContext()
: base("name=DbConnectionString")
{ }
public DbSet<Publisher> Publishers { get; set; }
public DbSet<Book> Books { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//For Identity Column (Primary Key)
modelBuilder.Entity<Publisher>().HasKey(p => p.PublisherId);
modelBuilder.Entity<Book>().HasKey(b => b.BookId);
//For Autogenerate of Primary Key
modelBuilder.Entity<Publisher>().Property(p => p.PublisherId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<Book>().Property(b => b.BookId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
//Relation ship of Tables
modelBuilder.Entity<Book>().HasRequired(p => p.Publisher).WithMany(b => b.Books).HasForeignKey(b => b.PublisherId);
base.OnModelCreating(modelBuilder);
}
}
public class Publisher
{
public int PublisherId { get; set; }
public string PublisherName { get; set; }
public string Address { get; set; }
public ICollection<Book> Books { get; set; }
}
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public string Year { get; set; }
public int PublisherId { get; set; }
public Publisher Publisher { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment