一,摘要
这是ASP.NET MVC中使用Nhibernate的第二部分,你也可以查看第一部分
一,多对多关联
我们将继续创建我们的Post类的映射文件,相对于Category将增加一点难度,应为我们不得不去呈现一个多对对的关系,为了达到这个目的,我们在映射文件中使用Bagyu元素,下面是Post.hbm.xml 文件的代码:
1: xml version="1.0" encoding="utf-8" ?> 2: <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" 3: namespace="Core.Domain.Model" 4: assembly="Core"> 5: 6: <class name="Post" table="Posts" dynamic-update="true"> 7: <cache usage="read-write"/> 8: <id name="Id" column="Id" type="Guid"> 9: <generator class="guid"/> 10: id> 11: <property name="Title" length="100"/> 12: <property name="Body"/> 13: <property name="CreationDate" type="datetime"/> 14: <property name="IsPublic" type="bool"/> 15: 16: <bag name="Categories" table="PostCategory" lazy="false" > 17: <key column="idPost" > key> 18: <many-to-many class="Category" column="idCategory" > many-to-many> 19: bag> 20: 21: class> 22: hibernate-mapping>bag元素包含在16-19行代码中,下面解释下上面的代码: 1.name属性是Post类的属性名,我们用来存储categories集合 2.table属性是数据库中的一个表,用来连接Post和Categories表 3.key中的column属性是Post的主键列 4.class属性是category模型的类名 5.many-to-many中的column属性是Categories的主键列 为了更好的理解这个映射文件,下面提供类图表和数据库图标:
从上面看到,我们不需创建PostCategory表的类
二,测试
下面提供完整的单元测试代码:
1: using System; 2: using System.Text; 3: using System.Collections.Generic; 4: using System.Linq; 5: using Microsoft.VisualStudio.TestTools.UnitTesting; 6: using Core.Domain.Model; 7: using Core.Domain.Repositories; 8: using Core; 9: amespace NHibernate101.Tests 10: 11: [TestClass] 12: public class RepositoriesTest 13: { 14: IRepository categoriesRepository; 15: IRepository postsRepository; 16: Post testPost; 17: Category testCategory1; 18: Category testCategory2; 19: 20: public RepositoriesTest() 21: { 22: } 23: private TestContext testContextInstance; 24: public TestContext TestContext 25: { 26: get 27: { 28: return testContextInstance; 29: } 30: set 31: { 32: testContextInstance = value; 33: } 34: } 35: [TestInitialize()] 36: public void CreateRepositories() 37: { 38: categoriesRepository = new CategoryRepository(); 39: postsRepository = new PostRepository(); 40: } 41: [TestMethod] 42: [DeploymentItem("hibernate.cfg.xml")] 43: public void CanCreateCategory() 44: { 45: testCategory1 = new Category() { Name = "ASP.NET" }; 46: categoriesRepository.Save(testCategory1); 47: 48: } 49: [TestMethod] 50: [DeploymentItem("hibernate.cfg.xml")] 51: public void CanCreatePost() 52: { 53: testPost = new Post(); 54: testPost.Title = "ASP.NET MVC and NHibernate"; 55: testPost.Body = "In this article I’m going to cover how to install and configure NHibernate and use it in a ASP.NET MVC application."; 56: testPost.CreationDate = DateTime.Now; 57: testPost.IsPublic = true; 58: testCategory2 = new Category() { Name= "ASP.NET MVC"}; 59: categoriesRepository.Save(testCategory2); 60: testPost.Categories.Add(testCategory2); 61: postsRepository.Save(testPost); 62: } 63: }如果上面的测试通过,我们将在数据库中看到新的post和categoty 随下的文章中我们将继续探索!