测试用的当前最新版本:

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-PC\GEOVIN;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-WEN\GEOVINDU")
.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;
}
}

  

查询中的实体关联及与储存过程操作还要继续。

  1. 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

Fluent NHibernate other example的更多相关文章

  1. 全自动迁移数据库的实现 (Fluent NHibernate, Entity Framework Core)

    在开发涉及到数据库的程序时,常会遇到一开始设计的结构不能满足需求需要再添加新字段或新表的情况,这时就需要进行数据库迁移. 实现数据库迁移有很多种办法,从手动管理各个版本的ddl脚本,到实现自己的mig ...

  2. 【翻译】Fluent NHibernate介绍和入门指南

    英文原文地址:https://github.com/jagregory/fluent-nhibernate/wiki/Getting-started 翻译原文地址:http://www.cnblogs ...

  3. Fluent Nhibernate之旅(五)--利用AutoMapping进行简单开发

    Fluent Nhibernate(以下简称FN)发展到如今,已经相当成熟了,在Nhibernate的书中也相应的推荐了使用FN来进行映射配置,之前写的FN之旅至今还有很多人会来私信我问题,说来惭愧, ...

  4. [Fluent NHibernate]第一个程序

    目录 写在前面 Fluent Nhibernate简介 基本配置 总结 写在前面 在耗时两月,NHibernate系列出炉这篇文章中,很多园友说了Fluent Nhibernate的东东,也激起我的兴 ...

  5. [Fluent NHibernate]一对多关系处理

    目录 写在前面 系列文章 一对多关系 总结 写在前面 上篇文章简单介绍了,Fluent Nhibernate使用代码的方式生成Nhibernate的配置文件,以及如何生成持久化类的映射文件.通过上篇的 ...

  6. Fluent NHibernate and Spring.net

    http://blog.bennymichielsen.be/2009/01/04/using-fluent-nhibernate-in-spring-net/ http://comments.gma ...

  7. Fluent NHibernate and Mysql,SQLite,PostgreSQL

    http://codeofrob.com/entries/sqlite-csharp-and-nhibernate.html https://code.google.com/archive/p/csh ...

  8. Fluent NHibernate关系映射

    1.好处:Fluent NHibernate让你不再需要去写NHibernate的标准映射文件(.hbm.xml), 方便了我们的代码重构,提供了代码的易读性,并精简了项目代码 实现: (1).首先我 ...

  9. fluent nhibernate 初体验

    离开.net框架两年时间,发展的很快呀.原先自我感觉良好到以为只差一个MVP的考核什么的,现在觉得真的差好远了. 呵呵,废话就不多说了.这次花了两天时间才拿下fluent nhibernate的fir ...

  10. Fluent NHibernate之旅

    Fluent NHibernate 之旅 导航篇: [原创]Fluent NHibernate之旅开篇: [原创]Fluent NHibernate之旅二--Entity Mapping: [原创]F ...

随机推荐

  1. 使用SQL Server 2014 In-Memory 内存数据库时需要注意的地方

    转载: http://www.infoq.com/cn/articles/sql-server-2014-memory-database http://www.cnblogs.com/Amaranth ...

  2. Maven3路程(三)用Maven创建第一个web项目(2)servlet演示

    上一章用Maven新建了web项目成功后,本文演示在此基础上应用servlet. 1.首先修改pom.xml文件,添加servlet依赖 <project xmlns="http:// ...

  3. Hybris电商方案介绍(企业全渠道) B2B B2C O2O建设

    1). 什么是Hybris: hybris software成立于1997年,2013年与SAP整合,成为SAP旗下的一份子,提供全渠道客户互动与商务解决方案,该解决方案能够为各机构提供客户的实时背景 ...

  4. oracle 数据库时间类型为字符串 时间范围大小查询

    select * from invoicedetail t2 where t2.Memo is null and to_char(to_date(t2.PrintDate,'yyyy-MM-dd hh ...

  5. U3D中IOS平台泛型方法尽少使用

    U3D的IOS最小运行库use micro mscorlib是不包含泛型反射方法的,如FieldType.GetGenericArguments方法.所以尽量少用List而直接使用array. 另外请 ...

  6. Shooting Algorithm

    Shooting算法是Wenjiang提出的一种优化Lasso(L1 Regularization)和Bridge Regression的算法, 本文以Lasso为例. 对于线性回归问题$\mathb ...

  7. WindowsServer2012桌面图标设置

    1.win+R调出运行窗口 2.输入:rundll32.exe shell32.dll,Control_RunDLL desk.cpl,,0 即可

  8. 从头构建自己的Linux系统

    2012-09-10        在博文“Linux系统启动过程分析”中我们了解了linux系统的启动流程,今天我们就来手动一步一步从头来构建一个最小的linux系统,然后用模拟器将其加载起来.常见 ...

  9. MINE

    MINE MINE is an app for the nearly 1.2 million songwriters, composers, musicians, and publishers who ...

  10. jquery---基本标签

    你觉得 jquery 有哪些好处? jQuery 是轻量级的 javascript 框架 强大的选择器 出色的 DOM 操作的封装 可靠的事件处理机制 完善的 ajax 封装 出色的浏览器的兼容性 支 ...