12

我在带有 c# 的 asp.net mvc3 中使用 Fluent Nhibernate

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

映射

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 视图

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);
 }
}
4

1 回答 1

16

视图的映射方式与表的映射方式相同,只是您应该放入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
}
于 2012-10-05T08:59:30.420 回答