我有以下表结构
Author[AuthorId,AuthorName];
Book [BookId, BookName, AuthorId];
已经为F.N映射创建了以下类
public class Author
{
public virtual int AuthorId { get; set; }
public virtual string AuthorName { get; set; }
public IList<Book> Book { get; set; }
}
public class AuthorDataMap : ClassMap<Auther>
{
public MaisonUserDataMap()
{
Table("author");
Id(x => x.AuthorId).Column("authorID");
Map(x => x.AuthorName).Column("authorName");
HasMany<MonsterData>(p => p.monsterData)
.KeyColumn("authorID")
.PropertyRef("AuthorId").Inverse();
}
public class Book
{
public virtual int BookId { get; set; }
public virtual string BookName { get; set; }
public virtual int AuthorId { get; set; }
public virtual Author Author { get; set; }
public Book()
{
Author = new Author();
}
}
class BookMap : ClassMap<Book>
{
public BookMap()
{
Table("book");
Id(x => x.BookId).Column("bookId");
Map(x => x.BookName).Column("bookName");
Map(x => x.AuthorId).Column("authorId");
References(x => x.Author);
}
}
使用以下NH查询,它将返回每个作者的单个对象及其相关书籍列表
var authorList = session.CreateCriteria<Auther>("AuthorList").Add(Restrictions.Eq("AuthorList.AuthorId", 1)).List<Author>(); // working
Console.WriteLine("AuthorList Count :" + authorList.Count);
foreach (var item in authorList)
{
foreach (var k in item.book)
{
Console.WriteLine("BookId :" + k.bookId);
}
}
现在我想获得具有作者详细信息的书籍对象列表。 (与上述相反)。我尝试使用以下代码执行此操作,但它没有返回任何作者详细信息
var bookList = session.CreateCriteria<Book>("Book").Add(Restrictions.Eq("Book.AuthorId", 1)).List<Book>();
Console.WriteLine("BookList Count :" + bookList.Count);
foreach (var item in bookList)
{
Console.WriteLine("BookId :" + item.bookId);
Console.WriteLine("AuthorName :" + item.Author.authorName);
}
如果有人知道怎么做,请告诉我。感谢
答案 0 :(得分:0)
如果我们想要使用一列映射到TWO属性,映射应如下所示:
public BookMap()
{
Table("book");
Id(x => x.BookId).Column("bookId");
Map(x => x.BookName).Column("bookName");
// authorId column for both
Map(x => x.AuthorId)
.Column("authorId")
.Not.Insert()
.Not.Update()
;
References(x => x.Author, "authorId");
}
所以,现在我们明确地说流利的NHibernate - 有“authorId”的值类型和引用类型表示。其中一个必须是readonly - 正确生成INSERT和UPDATE。
现在这个查询可以正常工作
var bookList = session
.CreateCriteria<Book>("Book")
.Add(Restrictions.Eq("Book.AuthorId", 1))
.List<Book>();
Console.WriteLine("BookList Count :" + bookList.Count);
foreach (var item in bookList)
{
Console.WriteLine("BookId :" + item.bookId);
Console.WriteLine("AuthorName :" + item.Author.authorName);
}
注意,另一方(作者)可以让HasMany现在定义没有属性ref
HasMany(a => a.Books)
.KeyColumn("authorID")
//.PropertyRef("AuthorId") // there will be Author reference
.Inverse();