0
我想學習流利,我想我會從一個簡單的例子開始。事實證明,我必須丟失一些東西,因爲流利程序一直試圖創建一個表格兩次,導致「數據庫中已經有一個名爲'作者'的對象。」流利的NHibernate Autmapping多對多
我有以下兩個數據類:
public class Author
{
public virtual int Id {get;set;}
public virtual string name {get;set;}
public virtual IList<Book> books { get;protected set; }
public Author()
{
books = new List<Book>();
}
public virtual void AddBook(Book book)
{
books.Add(book);
book.authors.Add(this);
}
}
public class Book
{
public virtual int Id { get; set; }
public virtual string name { get; set; }
public virtual IList<Author> authors {get; protected set; }
public Book()
{
authors = new List<Author>();
}
public virtual void AddAuthor(Author author)
{
authors.Add(author);
author.books.Add(this);
}
}
而且我提供以下覆蓋:
public class BooksOverride : IAutoMappingOverride<Book>
{
public void Override(AutoMapping<Book> mapping)
{
mapping.HasManyToMany(map => map.authors)
.Cascade.All()
.Inverse()
.Table("BooksAuthors");
}
}
public class AuthorOverride : IAutoMappingOverride<Author>
{
public void Override(AutoMapping<Author> mapping)
{
mapping.HasManyToMany(map => map.books).Cascade.All().Table("BooksAuthors");
}
}
這裏是插入代碼:
using (var session = HibernateHelper.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
var author1 = new Author { name = "john"};
var author2 = new Author { name = "william" };
var book1 = new Book { name = "A book"};
author1.AddBook(book1);
session.Save(author1);
transaction.Commit();
}
}
現在我不能爲我的生活找出爲什麼這不起作用!
看來我也有類似的問題是:Fluent Nhibernate Many to Many Mapping Way
,但我不知道如何解決它。也許這是與我使用automapping的事實有關?
如果有人有任何想法,我會非常感激。
非常感謝!