良好/简单的 asp.net mvc 应用程序与流畅的 nhibernate

发布于 2024-09-06 04:23:26 字数 62 浏览 3 评论 0原文

我在哪里可以找到一个好的/简单的 asp.net mvc 应用程序与流畅的 nhibernate?任何建议..

Where can i find a good/simple asp.net mvc application with fluent nhibernate? Any suggestion..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

◇流星雨 2024-09-13 04:23:26

我写了一个 示例 ASP.NET MVC 应用程序,它使用 FluentNHibernate 以及其他开源框架。 源代码位于


根据评论部分的要求,我尝试总结使用 ASP.NET MVC 设置 FluentNhibernate 的重要部分:

首先定义模型:

public class User
{
    public virtual int Id { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual int? Age { get; set; }
}

然后是允许您访问模型的存储库:

using System.Collections.Generic;

public interface IUsersRepository
{
    IEnumerable<User> GetUsers();
    User Get(int id);
    void Delete(int id);
    int Save(User user);
    void Update(User user);
}

然后实现此存储库:

using System.Collections.Generic;
using Spring.Data.NHibernate.Generic.Support;

public class SqlUsersRepository : HibernateDaoSupport, IUsersRepository
{
    public IEnumerable<User> GetUsers()
    {
        return HibernateTemplate.LoadAll<User>();
    }

    public User Get(int id)
    {
        return HibernateTemplate.Get<User>(id);
    }

    public void Delete(int id)
    {
        HibernateTemplate.Delete(new User { Id = id });
    }

    public int Save(User user)
    {
        return (int)HibernateTemplate.Save(user);
    }

    public void Update(User user)
    {
        HibernateTemplate.Update(user);
    }
}

到目前为止没有FluentNHibernate 特定部分。现在让我们定义映射:

using FluentNHibernate.Mapping;

public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Table("users");
        Id(x => x.Id, "usr_id");
        Map(x => x.FirstName, "usr_firstname");
        Map(x => x.LastName, "usr_lastname");
        Map(x => x.Age, "usr_age");
    }
}

以及一个使用 SQLite 的 Spring.NET 会话工厂,但您可以根据需要进行调整:

using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.ByteCode.Castle;
using NHibernate.Cfg;
using Spring.Data.NHibernate;

public class FluentSessionFactory : LocalSessionFactoryObject
{
    private readonly string _dataFile;
    public FluentSessionFactory(string dataFile)
    {
        _dataFile = dataFile;
    }

    protected override ISessionFactory NewSessionFactory(Configuration config)
    {
        return Fluently
            .Configure()
            .Database(
                SQLiteConfiguration
                    .Standard
                    .UsingFile(_dataFile)
                    .ProxyFactoryFactory<ProxyFactoryFactory>()
            ).Mappings(
                m => m.FluentMappings.AddFromAssemblyOf<UserMap>()
            ).BuildSessionFactory();
    }
}

接下来我们定义一个控制器:

public class HomeController : Controller
{
    private readonly IUsersRepository _repository;
    public HomeController(IUsersRepository repository)
    {
        _repository = repository;
    }

    public ActionResult Index()
    {
        return View(_repository.GetUsers());
    }
}

一旦我们完成所有这些,我们需要将各个部分连接在一起。当我们使用 Spring.NET 时,我们需要提供一个自定义控制器工厂:

public class SpringControllerFactory : DefaultControllerFactory
{
    private static readonly IApplicationContext _springContext = ContextRegistry.GetContext();

    protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
    {
        if (controllerType != null)
        {
            var objectsOfType = _springContext.GetObjectsOfType(controllerType);
            if (objectsOfType.Count > 0)
            {
                return (IController)objectsOfType.Cast<DictionaryEntry>().First<DictionaryEntry>().Value;
            }
        }
        return base.GetControllerInstance(requestContext, controllerType);
    }
}

接下来是 web.config:

<configuration>
  <configSections>
    <sectionGroup name="spring">
      <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
    </sectionGroup>
  </configSections>

  <spring>
    <context>
      <resource uri="~/Config/springContext.xml"/>
    </context>
  </spring>


  <system.web>
    <compilation debug="true">
      <assemblies>
        <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Web.Abstractions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </assemblies>
    </compilation>

    <pages>
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
      </namespaces>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>

最后是 springContext.xml:

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">

  <object
    id="siteRoot"
    type="System.Web.Hosting.HostingEnvironment, System.Web"
    factory-method="get_ApplicationPhysicalPath" />

  <object
    id="dataFile"
    type="System.IO.Path, mscorlib"
    factory-method="Combine">
    <constructor-arg name="path1" ref="siteRoot" />
    <constructor-arg name="path2" value="App_Data\data.db3" />
  </object>

  <object id="sessionFactory" type="AppName.Business.Repositories.FluentSessionFactory, AppName">
    <constructor-arg name="dataFile" ref="dataFile" />
  </object>

  <object id="sqlUsersRepository"
        type="AppName.Business.Repositories.SqlUsersRepository, AppName"
        singleton="false">
    <property name="SessionFactory" ref="sessionFactory"/>
  </object>

  <object id="home"
          type="AppName.Controllers.HomeController, AppName"
          singleton="false">
    <constructor-arg name="repository" ref="sqlUsersRepository" />
  </object>

</objects>

I wrote a sample ASP.NET MVC application which uses FluentNHibernate among other open source frameworks. The source code is available on github.


As requested in the comments section I've tried to summarize the important parts of setting FluentNhibernate with ASP.NET MVC:

Start by defining your model:

public class User
{
    public virtual int Id { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual int? Age { get; set; }
}

Then the repository that will allow you to access the model:

using System.Collections.Generic;

public interface IUsersRepository
{
    IEnumerable<User> GetUsers();
    User Get(int id);
    void Delete(int id);
    int Save(User user);
    void Update(User user);
}

Then implement this repository:

using System.Collections.Generic;
using Spring.Data.NHibernate.Generic.Support;

public class SqlUsersRepository : HibernateDaoSupport, IUsersRepository
{
    public IEnumerable<User> GetUsers()
    {
        return HibernateTemplate.LoadAll<User>();
    }

    public User Get(int id)
    {
        return HibernateTemplate.Get<User>(id);
    }

    public void Delete(int id)
    {
        HibernateTemplate.Delete(new User { Id = id });
    }

    public int Save(User user)
    {
        return (int)HibernateTemplate.Save(user);
    }

    public void Update(User user)
    {
        HibernateTemplate.Update(user);
    }
}

So far no FluentNHibernate specific parts. Let's define the mapping now:

using FluentNHibernate.Mapping;

public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Table("users");
        Id(x => x.Id, "usr_id");
        Map(x => x.FirstName, "usr_firstname");
        Map(x => x.LastName, "usr_lastname");
        Map(x => x.Age, "usr_age");
    }
}

And a Spring.NET session factory which uses SQLite but you could adapt as necessary:

using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.ByteCode.Castle;
using NHibernate.Cfg;
using Spring.Data.NHibernate;

public class FluentSessionFactory : LocalSessionFactoryObject
{
    private readonly string _dataFile;
    public FluentSessionFactory(string dataFile)
    {
        _dataFile = dataFile;
    }

    protected override ISessionFactory NewSessionFactory(Configuration config)
    {
        return Fluently
            .Configure()
            .Database(
                SQLiteConfiguration
                    .Standard
                    .UsingFile(_dataFile)
                    .ProxyFactoryFactory<ProxyFactoryFactory>()
            ).Mappings(
                m => m.FluentMappings.AddFromAssemblyOf<UserMap>()
            ).BuildSessionFactory();
    }
}

Next we define a controller:

public class HomeController : Controller
{
    private readonly IUsersRepository _repository;
    public HomeController(IUsersRepository repository)
    {
        _repository = repository;
    }

    public ActionResult Index()
    {
        return View(_repository.GetUsers());
    }
}

Once we have all this in place we need to plumb the pieces together. As we are using Spring.NET we need to provide a custom controller factory:

public class SpringControllerFactory : DefaultControllerFactory
{
    private static readonly IApplicationContext _springContext = ContextRegistry.GetContext();

    protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
    {
        if (controllerType != null)
        {
            var objectsOfType = _springContext.GetObjectsOfType(controllerType);
            if (objectsOfType.Count > 0)
            {
                return (IController)objectsOfType.Cast<DictionaryEntry>().First<DictionaryEntry>().Value;
            }
        }
        return base.GetControllerInstance(requestContext, controllerType);
    }
}

Next comes web.config:

<configuration>
  <configSections>
    <sectionGroup name="spring">
      <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
    </sectionGroup>
  </configSections>

  <spring>
    <context>
      <resource uri="~/Config/springContext.xml"/>
    </context>
  </spring>


  <system.web>
    <compilation debug="true">
      <assemblies>
        <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Web.Abstractions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </assemblies>
    </compilation>

    <pages>
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
      </namespaces>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>

And finally the springContext.xml:

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">

  <object
    id="siteRoot"
    type="System.Web.Hosting.HostingEnvironment, System.Web"
    factory-method="get_ApplicationPhysicalPath" />

  <object
    id="dataFile"
    type="System.IO.Path, mscorlib"
    factory-method="Combine">
    <constructor-arg name="path1" ref="siteRoot" />
    <constructor-arg name="path2" value="App_Data\data.db3" />
  </object>

  <object id="sessionFactory" type="AppName.Business.Repositories.FluentSessionFactory, AppName">
    <constructor-arg name="dataFile" ref="dataFile" />
  </object>

  <object id="sqlUsersRepository"
        type="AppName.Business.Repositories.SqlUsersRepository, AppName"
        singleton="false">
    <property name="SessionFactory" ref="sessionFactory"/>
  </object>

  <object id="home"
          type="AppName.Controllers.HomeController, AppName"
          singleton="false">
    <constructor-arg name="repository" ref="sqlUsersRepository" />
  </object>

</objects>
本宫微胖 2024-09-13 04:23:26

Orchard cms项目使用Fluent nhibernate。

http://orchard.codeplex.com/

The orchard cms project uses fluent nhibernate.

http://orchard.codeplex.com/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文