拥有图书课程。
public class Books
{
public virtual int Id { get; set; }
public virtual string Title { get; set; }
public virtual string Category { get; set; }
public virtual string ISBN { get; set; }
public virtual string Description { get; set; }
public virtual string Image { get; set; }
public virtual int CategoryId { get; set; }
public Categories Categories { get; set; }
public virtual IList<Comments> Comments { get; set; }
public Books()
{
Comments = new List<Comments>();
}
}
同样评论类。
public class Comments
{
public virtual int Id { get; set; }
public virtual string CommentText { get; set; }
public virtual DateTime Date { get; set; }
public virtual int IdBook { get; set; }
public Books Books { get; set; }
}
我的图书类地图代码:
public class BooksMap : ClassMap <Books>
{
public BooksMap()
{
Id(x => x.Id);
Map(x => x.Title);
Map(x => x.ISBN);
Map(x => x.Description);
Map(x => x.Category);
Map(x => x.Image);
Map(x => x.CategoryId);
//reference to categories
References(x => x.Categories).Column("Id").Not.Nullable();
//inverse reference (hasmany comments, rating)
HasMany(x => x.Comments).Cascade.All().Inverse();
}
}
同时评论地图&gt;
public class CommentsMap:ClassMap<Comments>
{
public CommentsMap()
{
Id(x => x.Id);
Map(x => x.CommentText);
Map(x => x.Date);
Map(x => x.IdBook);
References(x => x.Books).Column("Id").Not.Nullable();
}
}
我的问题是:我做得对吗? - 以及如何使用此映射进行查询,例如条件语言?
答案 0 :(得分:2)
很高兴知道什么不起作用(而不是问"is this ok?"
)
有一些摘要,可能是正确映射一对多和多对一的方法:
无论如何,所有属性都必须是虚拟的
public class Books
{
public virtual int Id { get; set; }
...
public virtual int CategoryId { get; set; }
// all must be virtual
//public Categories Categories { get; set; }
public virtual Categories Categories { get; set; }
public virtual IList<Comments> Comments { get; set; }
正如我们所看到的,还有CategoryId
和Category
- 一列的双倍映射(一次作为参考,一次作为ValueType)。这意味着,其中一个必须是只读的:
public BooksMap()
{
Id(x => x.Id);
...
// this should be readonly
// Map(x => x.CategoryId);
Map(x => x.CategoryId)
.Not.Update()
.Not.Insert();
//reference to categories
References(x => x.Categories)...
引用应该映射到代表Categroy_ID的列而不是Id (已经用于属性x.Id)
// this does not seem to be ok
References(x => x.Categories).Column("Id").Not.Nullable();
// we would need different column
References(x => x.Categories)
.Column("Category_ID")
.Not.Nullable();
我还希望,在Comments
表中有一些名为"Book_ID"
的列。这是列,我们将用于HasMany()
映射。
HasMany(x => x.Comments)
.KeyColumn("Book_ID")
.Cascade.AllDeleteOrphan()
.Inverse();
必须在另一侧使用相同的列“Book_ID”
public CommentsMap()
{
Id(x => x.Id);
...
References(x => x.Books)
.Column("Book_ID")
.Not.Nullable();
}
因此,此映射应该可以立即使用了。要获得有关查询的一些想法,请查看包含大量示例的文档: