csharp: NHibernate and Entity Framework (EF) (object-relational mapper)

时间:2023-02-12 10:49:56

代码生成器:

1. http://www.codesmithtools.com/

2.https://sourceforge.net/projects/mygeneration/

3. http://nmg.codeplex.com/  NHibernate Mapping Generator

https://github.com/luchen1021/NHibernateMappingGenerator

4.https://github.com/fdecaire/NHibernateMappingGenerator

http://www.mygenerationsoftware.com/templatelibrary/default.aspx

http://www.codeproject.com/Articles/629552/A-complete-guide-to-object-oriented-application-de

http://www.codeproject.com/Articles/656657/NET-Application-Framework-Spring-net-plus-ibatis-n

Nhibernate  Spring.net Nhibernate architecture  Castle.Net

/*
Domain:领域模型 (Model)
Entity
Mapping
  Dao:持久层 (Dal)
  Service:服务层(BLL)
  WebSite:表示层
  Common:通用类
  
  
Dao
DataAccess:用來存放實際要執行的SQL statement
Interface:用來定義DataAccess物件的介面
RowMapper:用來讓回傳的資料集合為物件型態
Domain
Interface:用來定義Domain object的屬性與行為的介面
Service
Interface:用來定義Service提供了哪些方法的介面

XML mapping, mapped classes
https://visualstudiogallery.msdn.microsoft.com/2049f26f-294a-40e0-94ca-fdd2d058217b

*/

http://www.cnblogs.com/wolf-sun/p/4068749.html
http://www.cnblogs.com/lyj/archive/2008/11/10/1330542.html
http://www.cnblogs.com/haogj/category/278985.html
http://www.oschina.net/p/nhibernate
http://www.cnblogs.com/GoodHelper/
http://springnetdemo1.googlecode.com/svn/trunk/
http://www.cnblogs.com/Leo_wl/p/5049799.html Spring.net-业务层仓储
https://dotblogs.com.tw/hatelove/archive/2009/09/17/10686.aspx
http://www.springframework.net/doc-latest/reference/html/tx-quickstart.html
https://dzone.com/articles/fluent-nhibernate-create-table
http://www.cnblogs.com/beniao/category/113253.html
https://catharsis.codeplex.com/
https://tinyerp.codeplex.com/

NHibernate 4.0

SQL创建表:

CREATE TABLE Class
(
ClassId INT NOT NULL IDENTITY PRIMARY KEY,
[Name] NVARCHAR(80) NOT NULL
)
GO CREATE TABLE Student
(
StudentID INT NOT NULL IDENTITY PRIMARY KEY,
[Name] NVARCHAR(100) NOT NULL,
ClassID INT NOT NULL
FOREIGN KEY REFERENCES Class(ClassId)
) INSERT INTO Class([Name]) VALUES(N'3班')
GO UPDATE Class SET [Name]=N'3班' WHERE ClassId=1 INSERT INTO Student([Name],ClassID) VALUES('geovindu',1)
GO

  用Mappings方便:(参数参考:https://www.devart.com/entitydeveloper/nhibernate-mapping-samples.html )

namespace Domain.Entities {

    public class Class {
public Class() { }
public virtual int ClassId { get; set; }
public virtual string Name { get; set; }
public virtual IList<Student> Student { get; set; }
}
} namespace Domain.Mappings { public class ClassMap : ClassMapping<Class> { public ClassMap() {
Schema("dbo");
Lazy(true);
Id(x => x.ClassId, map => map.Generator(Generators.Identity));
Property(x => x.Name, map => map.NotNullable(true));
//主键
Bag(x => x.Student, colmap => { colmap.Key(x => x.Column("ClassID")); colmap.Inverse(true); }, map => { map.OneToMany(); });
//Bag(x => x.Student, colmap => { colmap.Key(x => x.Column("ClassID")); colmap.Inverse(true); }, map => { map.OneToMany(); });
}
}
} namespace Domain.Entities { public class Student {
public virtual int StudentId { get; set; }
public virtual Class Class { get; set; }
public virtual string Name { get; set; }
public virtual int ClassId { get; set; } // namespace Domain.Mappings { /// <summary>
///
/// </summary>
public class StudentMap : ClassMapping<Student> { public StudentMap() {
Schema("dbo");
Lazy(true);
Id(x => x.StudentId, map => map.Generator(Generators.Identity));
Property(x => x.Name, map => map.NotNullable(true));
//外键
ManyToOne(x => x.Class, map => { map.Column("ClassID"); map.Cascade(Cascade.None); });
// ManyToOne(x => x.Class, map => { map.Column("ClassID"); map.Cascade(Cascade.None); }); //Bag(x => x.ClassId, x =>{x.Table("Class");x.Key(k => k.Column("ClassId"));}, x => x.OneToMany(k => k.Column("ClassId"))); //Bag(x => x.ClassId, colmap => { colmap.Key(x => x.Column("ClassID")); colmap.Inverse(true); }, map => { map.OneToMany(); }); //ManyToOne(x => x.Class, map =>
//{
// map.Column("ClassID");
// map.NotNullable(true);
// map.Cascade(Cascade.None);
//}); }
}
}

  老方法用XML文件:(比较麻烦)

hbm.xml:

<?xml version="1.0" encoding="utf-8" ?>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Domain" namespace="Domain">
<class name="Class" table="T_Class" lazy="true" >
<id name="ID" type="int" column="ClassID">
<generator class="native"/>
</id> <property name="Name" type="string">
<column name="Name" length="50"/>
</property>
<!--一对多关系:一个客户可以有一个或者多个订单-->
<!--子实体负责维护关联关系-->
<!--<set name="Class" table="Class" generic="true" inverse="true" cascade="all">
<key column="ClassId" foreign-key="FK__Student__ClassID__37A5467C"></key>
<one-to-many class="Domain.Class,Domain"/>
</set>-->
<!--<set name="Student" table="Student" generic="true" inverse="true" cascade="all">
<key column="StudentID" foreign-key="FK__Student__ClassID__37A5467C"></key>
<one-to-many class="Domain.Student,Domain"/>
</set>-->
</class>
</hibernate-mapping> <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Domain" namespace="Domain">
<class name="Student" table="T_Student" lazy="true" >
<id name="ID" type="int" column="StudentID">
<generator class="native"/>
<!--<generator class="assigned" />-->
</id> <property name="Name" type="string">
<column name="Name" length="50"/>
</property> <!--多对一关系:Orders属于一个Customer-->
<!--<many-to-one name="Class" column="ClassID" not-null="true"
class="Domain.Class,Domain"
foreign-key="FK__Student__ClassID__37A5467C" />-->
<many-to-one name="Class" column="ClassID" cascade="all"/> </class>
</hibernate-mapping>

  

另一种方法:

    [NHibernate.Mapping.Attributes.Class(Table = "UserData", NameType=typeof(User), Lazy=false)]
public class User
{
[NHibernate.Mapping.Attributes.Id(0, TypeType = typeof(long), Column = "ID", Name = "ID")]
[NHibernate.Mapping.Attributes.Generator(1, Class = "native")]
public virtual long ID { get; set; } [NHibernate.Mapping.Attributes.Property(Column = "UserName")]
public virtual string UserName { get; set; } [NHibernate.Mapping.Attributes.Property(Column = "Password")]
public virtual string Password { get; set; } [NHibernate.Mapping.Attributes.Property(Column = "FullName")]
public virtual string FullName { get; set; } [NHibernate.Mapping.Attributes.Property(Column = "Address")]
public virtual string Address { get; set; } [NHibernate.Mapping.Attributes.Property(Column = "Phone")]
public virtual string Phone { get; set; } [NHibernate.Mapping.Attributes.Property(Column = "Birthdate")]
public virtual DateTime? Birthdate { get; set; } [NHibernate.Mapping.Attributes.Property(Column = "Email")]
public virtual string Email { get; set; } [NHibernate.Mapping.Attributes.Property(Column = "IsSystemAdmin")]
public virtual bool IsSystemAdmin { get; set; } [NHibernate.Mapping.Attributes.ManyToOne(Column = "UserGroupID", Fetch = FetchMode.Join, ClassType=typeof(Group), Lazy = Laziness.False)]
public virtual Group Group { get; set; } [NHibernate.Mapping.Attributes.ManyToOne(Column = "DepartmentID", Fetch = FetchMode.Join, ClassType = typeof(Department), Lazy = Laziness.False)]
public virtual Department Department { get; set; } }

  

NHibernate Contrib https://sourceforge.net/projects/nhcontrib/?source=navbar
NHibernate.Envers https://bitbucket.org/RogerKratz/nhibernate.envers/src/d5e34a3f31ce?at=default

NSIS: Nullsoft Scriptable Install System
Windows installer development tool

https://sourceforge.net/p/nsis/code/HEAD/tarball

https://fnhsamples.codeplex.com/SourceControl/latest

https://code.google.com/p/nhibernate-repository-example/

https://github.com/jagregory/fluent-nhibernate

https://sourceforge.net/projects/nhibernate/files/NHibernate/

http://www.codeproject.com/Articles/21122/NHibernate-Made-Simple

http://www.c-sharpcorner.com/uploadfile/dpatra/using-nhibernate/

http://www.codeproject.com/Articles/363040/An-Introduction-to-Entity-Framework-for-Absolute-B

http://www.codeproject.com/Articles/464897/Object-Relational-Mapping-ORM-using-NHibernate-Par

https://entityframework.codeplex.com/

https://github.com/aspnet/EntityFramework

http://www.codeproject.com/Articles/26123/NHibernate-and-MySQL-A-simple-example

http://www.codeproject.com/Articles/14553/NHibernate-Helper-Kit

http://www.nhforge.org/wikis/howtonh/your-first-nhibernate-based-application.aspx

http://www.codeproject.com/Articles/17452/Eucalypto-ASP-NET-CMS-Library-using-NHibernate  (SQLite,SQL Server 2005,SQL Server 2000 ,MySQL)

http://www.codeproject.com/Articles/19425/NHibernate-Templates-for-Smart-Code-Generator

http://www.codeproject.com/Articles/55174/Custom-Fluent-Nhibernate-Membership-and-Role-Provi

http://www.codeproject.com/Articles/891056/Automatic-Table-Generation-in-any-database-by-NHib

http://www.codeproject.com/Articles/380022/Simplify-Database-Operations-with-Generic-Fluent-N

http://www.codeproject.com/Articles/14072/Building-a-Middle-Tier-Component-using-NHibernate

http://wcfbyexample.codeplex.com/  patterns & practices: WCF by example

http://www.codeproject.com/Articles/9243/PostgreSQL-libpqxx-Class-Generator

http://www.codeproject.com/Articles/1043625/Triggers-Rowcount-And-NHibernate

http://www.codeproject.com/Articles/48292/Three-tier-NET-Application-Utilizing-Three-ORM-T

http://microsoft.github.io/windows/

https://code.msdn.microsoft.com/site/search?f%5B0%5D.Type=SearchText&f%5B0%5D.Value=bing%20maps

http://cn.bing.com/dev/en-us/dev-center

http://kb.cnblogs.com/zt/ef/

http://kb.cnblogs.com/zt/nhibernate/

Entity Framework

http://learnentityframework.com/downloads/#2ed

Entity Framework

code first 

http://learnentityframework.com/downloads/#cfed

Pro Entity Framework 4.0

http://www.apress.com/9781590599907?gtmf=s

Entity Framework 4.0 Recipe

http://www.apress.com/9781430227038?gtmf=s

Entity Framework 6 Recipes

http://www.apress.com/9781430257882?gtmf=s

https://fnhsamples.codeplex.com/

https://github.com/nhibernate/nhibernate-core

https://www.packtpub.com/application-development/learning-nhibernate-4

http://echarts.baidu.com/examples.html

https://github.com/ecomfe/echarts

https://github.com/idoku/EChartsSDK

https://github.com/re-motion/Relinq

https://github.com/antlr/antlr3

https://github.com/zhang-xiao-ming/Dapper.Extensions

https://github.com/lobin-z0x50/DapperExamle

https://github.com/p-kaczynski/DapperSPMap

Dapper Stored Procedure Mapper

https://github.com/somdoron/DapperLinq

https://github.com/mrzeszowski/dapper-extensions-entityframework

https://github.com/IntertechInc/DapperParameters

https://github.com/castleproject

https://github.com/nhibernate/NHibernate.Spatial

https://github.com/zuifengke/windy-ibatisnet  搞定ibatis.net双数据库访问

https://github.com/alienblog/BaseFrame    spring.net,nhibernate,mvc 基础框架,三层架构扩展

简单灵活好用的数据库访问组件,比iBATIS.Net、Linq to Sql和Entity Framework好用  https://github.com/windeagle/StrongOrm

任务管理系统(ibatis框架) https://github.com/flowbywind/NewTaskSystem

Spring.NET NHibernate Northwind Reports using Aspose.Cells and Aspose.Pdf

https://code.msdn.microsoft.com/SpringNET-NHibernate-435c9f88#content

https://asposespringnet.codeplex.com/

https://www.devbridge.com/articles/entity-framework-6-vs-nhibernate-4/

Nhibernate 存储过程操作
http://www.codeproject.com/Articles/765862/Configuring-NHibernate-to-execute-a-Stored-Procedu
http://www.codeproject.com/Articles/37425/Execute-Stored-Procedure-in-SQL-Server-using-nHibe
http://www.martinwilley.com/net/code/nhibernate/sql.html

http://www.martinwilley.com/net/dotnet.html

    /// <summary>
///
/// </summary>
public interface ITextFormatter
{
string FormatText(string text);
string FormatSingular(string text);
string FormatPlural(string text); IList<string> PrefixRemovalList { get; set; }
} public abstract class AbstractTextFormatter : ITextFormatter
{
public virtual string FormatText(string text)
{
if (string.IsNullOrEmpty(text))
return text; var result = RemovePrefix(text); // Cannot have class or property with not allowed chars
result = result
.Replace("%", "Porcentaje") //Means Percentage in spanish
.Replace("á", "a")
.Replace("é", "e")
.Replace("í", "i")
.Replace("ó", "o")
.Replace("ú", "u"); // Split by capitals to preserve pascal/camelcasing in original text value
// Preserves TLAs. See http://*.com/a/1098039
result = Regex.Replace(result, "((?<=[a-z])[A-Z]|[A-Z](?=[a-z]))", " $1").Trim(); // Omit any chars except letters and numbers in class or properties.
result = result.Replace(" ", "_");
result = Regex.Replace(result, "[^a-zA-Z0-9_]", String.Empty); //And Underscore if (result.Length != 0 && char.IsNumber(result.ToCharArray(0, 1)[0]))
{
// Cannot start class or property with a number
result = "_" + result;
} return result;
} public string FormatSingular(string text)
{
return FormatText(text).MakeSingular();
} public string FormatPlural(string text)
{
return FormatText(text).MakePlural();
} private string RemovePrefix(string original)
{
if (PrefixRemovalList == null || PrefixRemovalList.Count == 0 || string.IsNullOrEmpty(original))
return original; // Strip out the first matching prefix
foreach (var prefix in PrefixRemovalList)
{
if (original.ToLower().StartsWith(prefix.ToLower()))
{
return original.Remove(0, prefix.Length);
}
} return original;
} public IList<string> PrefixRemovalList { get; set; }
} public class UnformattedTextFormatter : AbstractTextFormatter { } public class CamelCaseTextFormatter : AbstractTextFormatter
{
public override string FormatText(string text)
{
return base.FormatText(text).ToCamelCase();
}
} public class PascalCaseTextFormatter : AbstractTextFormatter
{
public override string FormatText(string text)
{
return base.FormatText(text).ToPascalCase();
}
} public class PrefixedTextFormatter : AbstractTextFormatter
{
public PrefixedTextFormatter(string prefix)
{
Prefix = prefix;
} private string Prefix { get; set; } public override string FormatText(string text)
{
return Prefix + base.FormatText(text);
}
} public static class TextFormatterFactory
{
public static ITextFormatter GetTextFormatter(ApplicationPreferences applicationPreferences)
{
ITextFormatter formatter;
switch(applicationPreferences.FieldNamingConvention)
{
case FieldNamingConvention.SameAsDatabase:
formatter = new UnformattedTextFormatter();
break;
case FieldNamingConvention.CamelCase:
formatter = new CamelCaseTextFormatter();
break;
case FieldNamingConvention.PascalCase:
formatter = new PascalCaseTextFormatter();
break;
case FieldNamingConvention.Prefixed:
formatter = new PrefixedTextFormatter(applicationPreferences.Prefix);
break;
default:
throw new Exception("Invalid or unsupported field naming convention.");
} formatter.PrefixRemovalList = applicationPreferences.FieldPrefixRemovalList; return formatter;
}
}
}