現有兩個表:user(用戶)和Blog(設置表),它們之間的關系正如我所說的是一對一的關系。現在我們來映射這兩個文件:
<?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="MyMvc4Project.Models" assembly="MyMvc4Project.Models"> <class name="MyMvc4Project.Models.User" table="Users" lazy="false"> <id name="Id"> <column name="Id" sql-type="varchar(40)" not-null="true"/> <generator class="uuid.hex" /> </id> <one-to-one name="Blog" class="Blog" cascade="all"></one-to-one> </class> </hibernate-mapping> <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="MyMvc4Project.Models" assembly="MyMvc4Project.Models"> <class name="MyMvc4Project.Models.Blog" table="Blog" lazy="false"> <id name="Id"> <column name="Id" sql-type="varchar(40)" not-null="true"/> <generator class="foreign"> <param name="property">User</param> </generator> </id> <one-to-one name="User" class="User" constrained="true"></one-to-one> </class> </hibernate-mapping>
現在測試如何保存數據:
var userDal = new UserDal(); var blogDal = new BlogDal(); var user = new User{ Name = name, Password = password, PostTitle = posttitle, CreateTime = DateTime.Now, Avatar = fileUrl }; var blog = new Blog { User = user }; user.Blog = blog; blogDal.Save(blog); userDal.Save(user);
總結:
查看本欄目