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());
}
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()
.Singleton()
.Use(CreateSessionFactory());
x.For()
.HttpContextScoped()
.Use(context => context.GetInstance().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()
.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
@{
ViewBag.Title = "Index";
}
Index
@foreach (var thing in Model)
{
@thing.Name}
New.cshtml
@model MySQLExample.Models.Thingy
@{
ViewBag.Title = "New";
}
New
@using (Html.BeginForm("Create", "Home")){
@Html.LabelFor(x => x.Name)
@Html.TextBoxFor(x => x.Name)
}
_Layout.cshtml
@ViewBag.Title@RenderBody()