ASP.NET MVC4整合NHibernate,FluentNHibernate,MySQL数据库的应用

时间:2022-09-22 07:31:50

Models层的类:

	public abstract class Entity
	{
		public virtual int Id { get; set; }
	}
        public class Thingy : Entity
	{
		public virtual string Name { get; set; }
	}
HomeController类如下:
public class HomeController : Controller
	{
		private ISession _session;

		public HomeController(ISession session)
		{
			_session = session;
		}

		public ActionResult Index()
		{
			return View(_session.Query<Thingy>());
		}

		public ActionResult New()
		{
			return View();
		}

		[HttpPost]
		public ActionResult Create(Thingy thing)
		{
			_session.SaveOrUpdate(thing);
			return RedirectToAction("Index");
		}
	}
Global.asax的内容如下:
public class MvcApplication : System.Web.HttpApplication
	{
		public static void RegisterGlobalFilters(GlobalFilterCollection filters)
		{
			filters.Add(new HandleErrorAttribute());
		}

		public static void RegisterRoutes(RouteCollection routes)
		{
			routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

			routes.MapRoute(
				"Default",
				"{controller}/{action}/{id}",
				new { controller = "Home", action = "Index", id = UrlParameter.Optional }
			);
		}

		protected void Application_Start()
		{
            //设置指定的控制器工厂
			ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());

			ObjectFactory.Initialize(x =>
			{
				x.For<ISessionFactory>()
					.Singleton()
					.Use(CreateSessionFactory());

				x.For<ISession>()
					.HttpContextScoped()
					.Use(context => context.GetInstance<ISessionFactory>().OpenSession());
			});

			AreaRegistration.RegisterAllAreas();

			RegisterGlobalFilters(GlobalFilters.Filters);
			RegisterRoutes(RouteTable.Routes);
		}

		protected void Application_EndRequest()
		{
			ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
		}

		protected ISessionFactory CreateSessionFactory()
		{
			string connectionString=ConfigurationManager.AppSettings["MYSQL_URI"];;
			var autoMap = AutoMap.AssemblyOf<Entity>()
				.Where(t => typeof(Entity).IsAssignableFrom(t));

			return Fluently.Configure()
				.Database(MySQLConfiguration.Standard.ConnectionString(connectionString))
                .Mappings(m => m.AutoMappings.Add(autoMap))  //FNT在映射的时候,分为Fluent Mapping(手动)和Auto Mapping(自动)两种方式
				.ExposeConfiguration(TreatConfiguration)
				.BuildSessionFactory();
		}

		protected virtual void TreatConfiguration(NHConfig.Configuration configuration)
		{
			var update = new SchemaUpdate(configuration);
			update.Execute(false, true);
		}
	}
StructureMapControllerFactory.cs
public class StructureMapControllerFactory : DefaultControllerFactory
	{
		public override IController CreateController(RequestContext requestContext, string controllerName)
		{
			try
			{
				var controllerType = base.GetControllerType(requestContext, controllerName);
				return ObjectFactory.GetInstance(controllerType) as IController;
			}
			catch (Exception)
			{
				return base.CreateController(requestContext, controllerName);
			}
		}
	}
Index.cshtml
@model IEnumerable<MySQLExample.Models.Thingy>

@{
	ViewBag.Title = "Index";
}

<h2>Index</h2>
<p>
	<a href="@Url.Action("New")">New thingy</a>
</p>
<ul>
	@foreach (var thing in Model)
	{
		<li>@thing.Name</li>
	}
</ul>
New.cshtml
@model MySQLExample.Models.Thingy

@{
	ViewBag.Title = "New";
}

<h2>New</h2>
<div>
	@using (Html.BeginForm("Create", "Home")){
		<p>
			@Html.LabelFor(x => x.Name)
			@Html.TextBoxFor(x => x.Name)
		</p>
		<p>
			<input type="submit" value="Submit" />
		</p>
	}
</div>
_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<title>@ViewBag.Title</title>
	<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
</head>

<body>
	@RenderBody()
</body>
</html>