I'm a NHibernate novice trying to configure an existing database with Fluent NHibernate. The problem is with a many-to-many mapping, in this example represented by libraries and books. I guess this should be really basic stuff, but I get the following exception:
FluentNHibernate.Cfg.FluentConfigurationException: An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.
---> NHibernate.MappingException: Repeated column in mapping for collection: MvcNhibernatePoc.Models.Book.Libraries column: BookId
The structure of the database should not be changed and looks something like:
Table **Book**
BookId (int)
BookName (varchar(255))
Table **Library**
LibraryId (int)
LibraryName (varchar(255))
Table **Book_Library**
Id (int)
BookId (int)
LibraryId (int)
Based on this I have created the following domain classes:
public class Library
{
public virtual int LibraryId { get; set; }
public virtual string Name { get; set; }
public virtual IList<Book> Books { get; set; }
public Library()
{
Books = new List<Book>();
}
}
public class Book
{
public virtual int BookId { get; set; }
public virtual string Name { get; set; }
public virtual IList<Library> Libraries { get; set; }
public Book()
{
Libraries = new List<Library>();
}
}
Mapping:
public class LibraryMap : ClassMap<Library>
{
public LibraryMap()
{
Table("Library");
Id(l => l.LibraryId).Column("LibraryId");
Map(l => l.Name).Column("LibraryName");
HasManyToMany<Book>(l => l.Books)
.Table("Book_Library")
.ParentKeyColumn("LibraryId")
.ChildKeyColumn("LibraryId")
.Cascade.SaveUpdate();
}
}
public class BookMap : ClassMap<Book>
{
public BookMap()
{
Table("Book");
Id(b => b.BookId).Column("BookId");
Map(b => b.Name).Column("BookName");
HasManyToMany<Library>(b => b.Libraries)
.Table("Book_Library")
.ParentKeyColumn("BookId")
.ChildKeyColumn("BookId")
.Cascade.SaveUpdate()
.Inverse();
}
}
Fluent configuration:
Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008.ConnectionString(conString).ShowSql)
.Mappings(m => m.FluentMappings
.AddFromAssemblyOf<Library>())
.BuildSessionFactory();
And finally my failing testcode:
var library = new Library { LibraryId = 1, Name = "Alexandria library"};
var book = new Book { BookId = 1, Name = "Pyramids for dummies" };
library.Books.Add(book);
book.Libraries.Add(library);
using (var session = NHibernateHelper.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
session.Save(library);
session.Flush();
transaction.Commit();
Console.WriteLine("Saved library " + library.Name);
}
}
.ParentKeyColumn("BookId")
.ChildKeyColumn("BookId")
.ParentKeyColumn("LibraryId")
.ChildKeyColumn("LibraryId")
should be
// BookMap
.ParentKeyColumn("BookId")
.ChildKeyColumn("LibraryId")
// LibraryMap
.ParentKeyColumn("LibraryId")
.ChildKeyColumn("BookId")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With