我正在努力学习流利,我想我会从一个简单的例子开始。事实证明我一定遗漏了一些东西,因为 fluent 不断尝试创建一个表两次,导致“数据库中已经有一个名为‘作者’的对象。”
我有以下两个数据类:
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
但我不知道如何解决它。也许这与我使用自动映射的事实有关?
如果有人有任何想法,我将不胜感激。
非常感谢!