测试用的当前最新版本:
sql:
--- CREATE TABLE Users ( UserID INT IDENTITY(1,1) PRIMARY KEY, [Name] VARCHAR(50) NULL, [No] VARCHAR(50) NULL ) GO INSERT INTO Users([Name],[NO]) VALUES('geovindu','001') INSERT INTO Users([Name],[NO]) VALUES('sibodu','002') select * FROM dbo.Users CREATE TABLE Projects ( ProjectID INT IDENTITY(1,1) PRIMARY KEY, [Name] VARCHAR(50) NULL, UserID INT FOREIGN KEY REFERENCES Users(UserID) ) GO INSERT INTO Projects([Name],UserID) VALUES('中考',1) INSERT INTO Projects([Name],UserID) VALUES('高考',1) INSERT INTO Projects([Name],UserID) VALUES('小考',2) select * FROM dbo.UserDetails CREATE TABLE UserDetails ( UserID INT FOREIGN KEY REFERENCES Users(UserID), Sex INT NULL, Age INT NULL, BirthDate DATETIME DEFAULT(GETDATE()), Height DECIMAL(6,2) DEFAULT(0) ) GO INSERT INTO UserDetails(UserID,Sex,Age,BirthDate,Height) VALUES(1,1,40,'1977-02-14',172.01) INSERT INTO UserDetails(UserID,Sex,Age,BirthDate,Height) VALUES(2,1,10,'2007-12-07',122.01) CREATE TABLE Product ( ProductID INT IDENTITY(1,1) PRIMARY KEY, [Name] VARCHAR(50) NULL, Color VARCHAR(50) NULL ) GO INSERT INTO Product([Name],Color) VALUES('电视机','黑色') INSERT INTO Product([Name],Color) VALUES('洗碗机','白色') INSERT INTO Product([Name],Color) VALUES('微波炉','白色') INSERT INTO Product([Name],Color) VALUES('笔记本','红色') INSERT INTO Product([Name],Color) VALUES('电脑','红色') INSERT INTO Product([Name],Color) VALUES('办公桌','红色') INSERT INTO Product([Name],Color) VALUES('轿车','红色') INSERT INTO Product([Name],Color) VALUES('笔','红色') INSERT INTO Product([Name],Color) VALUES('纸张','红色') CREATE TABLE ProjectProduct ( ProjectID INT FOREIGN KEY REFERENCES Projects(ProjectID), ProductID INT FOREIGN KEY REFERENCES Product(ProductID) ) GO INSERT INTO ProjectProduct(ProjectID,ProductID) VALUES(1,2) INSERT INTO ProjectProduct(ProjectID,ProductID) VALUES(1,3) INSERT INTO ProjectProduct(ProjectID,ProductID) VALUES(1,4) INSERT INTO ProjectProduct(ProjectID,ProductID) VALUES(1,6) INSERT INTO ProjectProduct(ProjectID,ProductID) VALUES(2,1) INSERT INTO ProjectProduct(ProjectID,ProductID) VALUES(2,2) INSERT INTO ProjectProduct(ProjectID,ProductID) VALUES(2,3) INSERT INTO ProjectProduct(ProjectID,ProductID) VALUES(2,4) INSERT INTO ProjectProduct(ProjectID,ProductID) VALUES(2,7) INSERT INTO ProjectProduct(ProjectID,ProductID) VALUES(2,8) CREATE TABLE Tasks ( TaskID INT IDENTITY(1,1) PRIMARY KEY, [Name] VARCHAR(50) NULL, ProjectID INT FOREIGN KEY REFERENCES Projects(ProjectID) ) GO INSERT INTO Tasks([Name],ProjectID) VALUES('提醒交货',1) INSERT INTO Tasks([Name],ProjectID) VALUES('提醒验收',2)
Entities (Model)
/// <summary> /// /// </summary> public abstract class Entity { virtual public int ID { get; set; } } public class User : Entity { virtual public string Name { get; set; } public virtual string No { get; set; } public virtual UserDetails UserDetails { get; set; } } public class Project : Entity { public Project() { Task = new List<Task>(); Product = new List<Product>(); } public virtual string Name { get; set; } public virtual User User { get; set; } public virtual IList<Product> Product { get; set; } public virtual IList<Task> Task { get; protected set; } } public class Product : Entity { public Product() { Project = new List<Project>(); } public virtual IList<Project> Project { get; set; } public virtual string Name { get; set; } public virtual string Color { get; set; } } public class Task : Entity { public virtual string Name { get; set; } public virtual Project Project { get; set; } } public class UserDetails : Entity { public virtual User User { get; set; } public virtual int Sex { get; set; } public virtual int Age { get; set; } public virtual DateTime BirthDate { get; set; } public virtual decimal Height { get; set; } }
Mapping:
各关联主键外键表设计参考:
http://www.codeproject.com/Articles/232034/Inheritance-mapping-strategies-in-Fluent-Nhibernat
https://www.devbridge.com/articles/entity-framework-6-vs-nhibernate-4/
http://blog.devart.com/support-of-many-to-one-mapping-for-component-navigation-properties-in-entity-developer.html
https://www.devart.com/entitydeveloper/nhibernate-mapping-samples.html
http://www.codeproject.com/Articles/19425/NHibernate-Templates-for-Smart-Code-Generator
http://www.codeproject.com/Articles/247196/Components-Mapping-in-Fluent-NHibernate
http://www.codeproject.com/Articles/232034/Inheritance-mapping-strategies-in-Fluent-Nhibernat
//one to one /// <summary> /// /// </summary> public class UsersMapping : ClassMap<User> { public UsersMapping() { Table("Users"); LazyLoad(); Id(x => x.ID).Column("UserID").GeneratedBy.Identity(); HasOne(x => x.UserDetails).Cascade.All().PropertyRef("User"); //多对一 Map(x => x.Name).Nullable(); Map(x => x.No).Nullable(); } } public class UserDetailsMapping : ClassMap<UserDetails> { public UserDetailsMapping() { Table("UserDetails"); LazyLoad(); Id(x => x.ID).Column("UserID").GeneratedBy.Foreign("User"); Map(x => x.Height).Nullable(); Map(x => x.Age).Nullable(); Map(x => x.Sex).Nullable(); Map(x => x.BirthDate).Nullable(); HasOne(x => x.User).Cascade.All();// } } //one to more /// <summary> /// /// </summary> public class TasksMappping : ClassMap<Task> { public TasksMappping() { Table("Tasks"); LazyLoad(); Id(x => x.ID).Column("TaskID").GeneratedBy.Identity(); References(x => x.Project).Nullable().Column("ProjectID").Cascade.None(); Map(x => x.Name).Nullable(); } } /// <summary> /// /// </summary> //public class ProjectsMapping : ClassMap<Project> //{ // public ProjectsMapping() // { // Table("Projects"); // LazyLoad(); // Id(x => x.ID).Column("ProjectID").GeneratedBy.Identity(); // References(x => x.User).Column("UserID").Cascade.None(); // Map(x => x.Name).Nullable(); // HasMany(x => x.Task).KeyColumn("ProjectID").LazyLoad().Cascade.SaveUpdate(); // } //} //more to more public class ProjectsMapping : ClassMap<Project> { public ProjectsMapping() { Table("Projects"); LazyLoad(); Id(x => x.ID).Column("ProjectID").GeneratedBy.Identity(); References(x => x.User).Column("UserID").Cascade.None(); Map(x => x.Name).Nullable(); HasMany(x => x.Task).KeyColumn("ProjectID").LazyLoad().Cascade.SaveUpdate();//一多对 HasManyToMany(x => x.Product).ParentKeyColumn("ProjectID").ChildKeyColumn("ProductID").Table("ProjectProduct");//多对多 } } public class ProductMapping : ClassMap<Product> { public ProductMapping() { Table("Product"); Id(x => x.ID).Column("ProductID").GeneratedBy.Identity(); Map(x => x.Name).Nullable(); Map(x => x.Color).Nullable(); HasManyToMany(x => x.Project).ParentKeyColumn("ProductID").ChildKeyColumn("ProjectID").Table("ProjectProduct");//多对多 } }
/// <summary> /// /// </summary> public partial class Form1 : Form { /// <summary> /// /// </summary> public Form1() { InitializeComponent(); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Form1_Load(object sender, EventArgs e) { } /// <summary> /// 一对一映射 /// 添加记录 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { try { // var session = NHibernateHelper.GetSession(); if (!object.Equals(session, null)) { //get user from database User user1 = session.Load<User>(1); //save the User data session.Transaction.Begin(); User user = new User() { Name = "White", No = "8888" }; UserDetails userDetails = new UserDetails() { Age = 18, BirthDate = DateTime.Now.Date, Height = 140, Sex = 2 }; user.UserDetails = userDetails; userDetails.User = user; session.Save(user); session.Transaction.Commit(); } } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } } /// <summary> /// 一对多/多对一 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { var session = NHibernateHelper.GetSession(); Project project = session.Get<Project>(1); //save the User data session.Transaction.Begin(); Task task = new Task() { Name = "create", Project = project }; session.Save(task); session.Transaction.Commit(); Task task1 = session.Get<Task>(1); } /// <summary> /// 多对多 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button3_Click(object sender, EventArgs e) { // var session = NHibernateHelper.GetSession(); session.Transaction.Begin(); //get the Project ICriteria query = session.CreateCriteria<Project>(); IList<Project> projects = query.List<Project>(); //create the Product Product product = new Product() { Name = "Product1", Color = "Red" }; product.Project = projects; session.Save(product); session.Transaction.Commit(); } }
/// <summary> /// FluentNHibernate /// /// </summary> public class NHibernateHelper { private static ISessionFactory _sessionFactory; private static ISession _session; private static object _objLock = new object(); /// <summary> /// /// </summary> private NHibernateHelper() { } /// <summary> /// 创建ISessionFactory /// </summary> /// <returns></returns> public static ISessionFactory GetSessionFactory() { if (_sessionFactory == null) { lock (_objLock) { if (_sessionFactory == null) { //配置ISessionFactory //_sessionFactory = (new Configuration()).Configure().BuildSessionFactory(); _sessionFactory = InitializeSessionFactory(); } } } return _sessionFactory; } /// <summary> /// /// </summary> private static ISessionFactory InitializeSessionFactory() { _sessionFactory = Fluently.Configure() .Database(MsSqlConfiguration.MsSql2005.ConnectionString(@"Server=GEOVINDU-PCGEOVIN;initial catalog=NHibernateSimpleDemo;User ID=sa;Password=520;").ShowSql()) .Mappings(m => m.FluentMappings.AddFromAssemblyOf<NHibernateHelper>()) //.ExposeConfiguration(c => new SchemaExport(c).Create(true, true)) //会清除数据 .BuildSessionFactory(); return _sessionFactory; } /// <summary> /// /// </summary> private static ISessionFactory InitializeSessionFactoryP() { _sessionFactory = Fluently.Configure() .Database(MsSqlConfiguration.MsSql2005.ConnectionString (s => s.Server(@"LF-WENGEOVINDU") .Database("NHibernateSimpleDemo") .Username("sa") .Password("520") ).ShowSql()) .Mappings(m => m.FluentMappings.AddFromAssemblyOf<NHibernateHelper>()) //.ExposeConfiguration(c => new SchemaExport(c).Create(true, true)) //会清除数据 .BuildSessionFactory(); return _sessionFactory; } /// <summary> /// 打开ISession /// </summary> /// <returns></returns> public static ISession GetSession() { _sessionFactory = GetSessionFactory(); if (_session == null) { lock (_objLock) { if (_session == null) { _session = _sessionFactory.OpenSession(); } } } return _session; } }
查询中的实体关联及与储存过程操作还要继续。
-
MVC(Model-View-Controller) 架構適合於大型系統,它可以分層且可以在實體層面切割為不同的機器或服務,只要彼此間具有適當的通訊協定即可。MVVM(Model-View-ViewModel) 架構適合像 XAML 這種與程式碼無關 (code ignorance) 的使用者介面設計,只要 View 中下特定的指令與 ViewModel 串接,就可以享有 ViewModel 溝通的功能,而 ViewModel 只需做一些特別的介面實作,即可平順的和 View 溝通。MVP(Model-View-Presenter) 架構適合集中由程式碼決定 View 動作的應用程式,而 View 只需要實作特定的介面即可,不需要太複雜的工作,但 Presenter 則可能會受限於 View 介面的動作,而無法做更進一步對 View 的控制。
Reference:
http://en.wikipedia.org/wiki/Model-view-presenter
http://en.wikipedia.org/wiki/Model-view-controller
http://en.wikipedia.org/wiki/Model_View_ViewModel