Saturday, July 16, 2011

NHibernate equivalent of Entity Framework's MapLeftKey and MapRightKey

Fluent NHibernate equivalent of Entity Framework's MapLeftKey and MapRightKey


.Override<Movie>(x => x.HasManyToMany(y => y.Genres).Table("MovieAssocGenre")        
    .ParentKeyColumn("z_MovieId").ChildKeyColumn("z_GenreId"))
.Override<Genre>(x => x.HasManyToMany(y => y.Movies).Table("MovieAssocGenre")
    .ParentKeyColumn("z_GenreId").ChildKeyColumn("z_MovieId"))


And EntityFramework equivalent of NHibernate's ParentKeyColumn and ChildKeyColumn

// You can either do this:
modelBuilder.Entity<Movie>().HasMany(x => x.Genres).WithMany(x => x.Movies).Map(x =>
 {
  x.ToTable("MovieAssocGenre");
  x.MapLeftKey("z_MovieId");
  x.MapRightKey("z_GenreId");
 });

// Or this:
modelBuilder.Entity<Genre>().HasMany(x => x.Movies).WithMany(x => x.Genres).Map(x =>
 {
  x.ToTable("MovieAssocGenre");
  x.MapLeftKey("z_GenreId");
  x.MapRightKey("z_MovieId");
 });


// In Entity Framework, there's no need to do both statements, just choose one. Any of those statement fully describes the many-to-many on both ends

// Whereas in NHibernate, you need to do both

The DDL:

create table Movie
(
MovieId int identity(1,1) not null primary key,
MovieName varchar(100) not null unique,
MovieDescription varchar(100) not null unique,
YearReleased int not null,
Version rowversion
);

create table Genre
(
GenreId int identity(1,1) not null primary key,
GenreName varchar(100) not null unique
);


create table MovieAssocGenre
(
MovieAssocGenreId int identity(1,1) not null primary key,
z_MovieId int not null references Movie(MovieId),
z_GenreId int not null references Genre(GenreId),
constraint uk_MovieAssocGenre unique(z_MovieId, z_GenreId)
);

No comments:

Post a Comment