Sql视图的流畅Nhibernate映射

时间:2012-10-05 08:45:38

标签: asp.net-mvc nhibernate fluent-nhibernate nhibernate-mapping fluent-nhibernate-mapping

我在asp.net mvc3中使用Fluent Nhibernate和c#

我正在按照以下方式生成并映射一个类

映射

using FluentNHibernate.Mapping;
using Com.Web.Domain;

   namespace Com.Web.Mapping
      {
         public class CompanyMap : ClassMap<Company>
        {
             public CompanyMap()
            {
               Id(x => x.id);
               Map(x => x.Name);
              }
          }
       }

     using System.Collections.Generic;
     using System;

      namespace Com.Web.Domain
      {

          public class Company
         {

          public virtual int id { get; set; }
          public virtual string Name{get;set}

           }

        }

并在配置文件中

  private static void InitializeSessionFactory()
    {

       _sessionFactory = Fluently.Configure()
            .Database(MsSqlConfiguration.MsSql2008
                          .ConnectionString(local)

            )
            .Mappings(m =>
                      m.FluentMappings
                          .AddFromAssemblyOf<Company>())
            .ExposeConfiguration(cfg => new SchemaExport(cfg)
            .Create(false, false))  // this is intentionally set false , bcz i dont want to regenerate table when application starts every time 
            .BuildSessionFactory();


    }

现在问题来了我在sql中创建一个看起来像这样的视图

Sql View

CREATE VIEW [FeaturedCompanies] AS

   SELECT COUNT(Company.id) As Count FROM Company
   WHERE Name='Alias'

我想在我的代码中使用此视图,就像我正在使用但我怎么能这样做,我搜索了很多,但在谷歌上找不到任何东西

请尽快帮助我,并提前致谢

到目前为止尝试的内容

public class FeaturedCompany
{
    public virtual int id { get; set; }
    public virtual int name { get; set; }
    public virtual int count { get; set; }
}

映射

public class FeaturedCompanyMap : ClassMap<FeaturedCompany>
  {
 public FeaturedCompanyMap()
 {
    Table("FeaturedCompanies");
    ReadOnly();
   Id(x => x.id);
   Map(x => x.name);
   Map(x => x.count);
 }
}

1 个答案:

答案 0 :(得分:14)

视图的映射方式与映射表的方式相同,只是您应该在映射中放置Readonly()以防止意外写入。例如:

public class FeaturedCompanyMap : ClassMap<FeaturedCompany>
{
    public FeaturedCompanyMap ()
    {
       Table("FeaturedCompanies");
       ReadOnly();

       Id(x => x.Id);
       Map(x => x.Name);
       Map(x => x.Count);
    }
}

更新:获取计数

var results = session.Query<FeaturedCompany>().Where(filter).List();

foreach(var row in results.Select(r => "Alias: " + r.Name + "  Occurence: " + r.Count))
{
    // print row to screen
}