问答文章1 问答文章501 问答文章1001 问答文章1501 问答文章2001 问答文章2501 问答文章3001 问答文章3501 问答文章4001 问答文章4501 问答文章5001 问答文章5501 问答文章6001 问答文章6501 问答文章7001 问答文章7501 问答文章8001 问答文章8501 问答文章9001 问答文章9501

activerecord 中如何将视图映射为类

发布网友 发布时间:2022-05-01 10:47

我来回答

2个回答

懂视网 时间:2022-05-01 15:08

  1. 开发工具VS2015,Sql Server2008R2

  2. 新建数据库,数据初始化脚本如下:

 1 --新建数据库Castle.ActiveRecord.DB1
 2 CREATE DATABASE [Castle.ActiveRecord.DB1];
 3 GO
 4 
 5 USE [Castle.ActiveRecord.DB1]
 6 GO
 7 /****** Object: Table [dbo].[Post] Script Date: 09/25/2016 16:46:21 ******/
 8 SET ANSI_NULLS ON
 9 GO
10 SET QUOTED_IDENTIFIER ON
11 GO
12 CREATE TABLE [dbo].[Post](
13 [Id] [int] IDENTITY(1,1) NOT NULL,
14 [Subject] [nvarchar](64) NULL,
15 [Text] [nvarchar](1024) NULL,
16 [DateAdded] [datetime] NULL,
17 PRIMARY KEY CLUSTERED 
18 (
19 [Id] ASC
20 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
21 ) ON [PRIMARY]
22 GO
23 EXEC sys.sp_addextendedproperty @name=N‘MS_Description‘, @value=N‘自增主键‘ , @level0type=N‘SCHEMA‘,@level0name=N‘dbo‘, @level1type=N‘TABLE‘,@level1name=N‘Post‘, @level2type=N‘COLUMN‘,@level2name=N‘Id‘
24 GO
25 EXEC sys.sp_addextendedproperty @name=N‘MS_Description‘, @value=N‘主题‘ , @level0type=N‘SCHEMA‘,@level0name=N‘dbo‘, @level1type=N‘TABLE‘,@level1name=N‘Post‘, @level2type=N‘COLUMN‘,@level2name=N‘Subject‘
26 GO
27 EXEC sys.sp_addextendedproperty @name=N‘MS_Description‘, @value=N‘内容‘ , @level0type=N‘SCHEMA‘,@level0name=N‘dbo‘, @level1type=N‘TABLE‘,@level1name=N‘Post‘, @level2type=N‘COLUMN‘,@level2name=N‘Text‘
28 GO
29 EXEC sys.sp_addextendedproperty @name=N‘MS_Description‘, @value=N‘添加日期‘ , @level0type=N‘SCHEMA‘,@level0name=N‘dbo‘, @level1type=N‘TABLE‘,@level1name=N‘Post‘, @level2type=N‘COLUMN‘,@level2name=N‘DateAdded‘
30 GO
31 SET IDENTITY_INSERT [dbo].[Post] ON
32 INSERT [dbo].[Post] ([Id], [Subject], [Text], [DateAdded]) VALUES (1, N‘新闻‘, N‘最新新闻内容‘, ‘2016-09-01‘)
33 INSERT [dbo].[Post] ([Id], [Subject], [Text], [DateAdded]) VALUES (2, N‘音乐‘, N‘流行音乐‘, ‘2016-09-02‘)
34 SET IDENTITY_INSERT [dbo].[Post] OFF
35 
36 --新建数据库Castle.ActiveRecord.DB2
37 CREATE DATABASE [Castle.ActiveRecord.DB2];
38 GO
39 
40 USE [Castle.ActiveRecord.DB2]
41 GO
42 /****** Object: Table [dbo].[Post] Script Date: 09/25/2016 16:53:05 ******/
43 SET ANSI_NULLS ON
44 GO
45 SET QUOTED_IDENTIFIER ON
46 GO
47 CREATE TABLE [dbo].[Post](
48 [Id] [int] IDENTITY(1,1) NOT NULL,
49 [Subject] [nvarchar](64) NULL,
50 [Text] [nvarchar](1024) NULL,
51 [DateAdded] [datetime] NULL,
52 PRIMARY KEY CLUSTERED 
53 (
54 [Id] ASC
55 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
56 ) ON [PRIMARY]
57 GO
58 EXEC sys.sp_addextendedproperty @name=N‘MS_Description‘, @value=N‘自增主键‘ , @level0type=N‘SCHEMA‘,@level0name=N‘dbo‘, @level1type=N‘TABLE‘,@level1name=N‘Post‘, @level2type=N‘COLUMN‘,@level2name=N‘Id‘
59 GO
60 EXEC sys.sp_addextendedproperty @name=N‘MS_Description‘, @value=N‘主题‘ , @level0type=N‘SCHEMA‘,@level0name=N‘dbo‘, @level1type=N‘TABLE‘,@level1name=N‘Post‘, @level2type=N‘COLUMN‘,@level2name=N‘Subject‘
61 GO
62 EXEC sys.sp_addextendedproperty @name=N‘MS_Description‘, @value=N‘内容‘ , @level0type=N‘SCHEMA‘,@level0name=N‘dbo‘, @level1type=N‘TABLE‘,@level1name=N‘Post‘, @level2type=N‘COLUMN‘,@level2name=N‘Text‘
63 GO
64 EXEC sys.sp_addextendedproperty @name=N‘MS_Description‘, @value=N‘添加日期‘ , @level0type=N‘SCHEMA‘,@level0name=N‘dbo‘, @level1type=N‘TABLE‘,@level1name=N‘Post‘, @level2type=N‘COLUMN‘,@level2name=N‘DateAdded‘
65 GO
66 SET IDENTITY_INSERT [dbo].[Post] ON
67 INSERT [dbo].[Post] ([Id], [Subject], [Text], [DateAdded]) VALUES (1, N‘小说‘, N‘纪实小说‘, ‘2016-09-03‘)
68 INSERT [dbo].[Post] ([Id], [Subject], [Text], [DateAdded]) VALUES (2, N‘电脑‘, N‘超极本‘, ‘2016-09-04‘)
69 SET IDENTITY_INSERT [dbo].[Post] OFF

    3.新建MVC项目ActiveRecord.Demo,新建类库Castle.ActiveRecord.DB1.Models,类库Castle.ActiveRecord.DB2.Models

  • MVC项目ActiveRecord.Demo文件添加Castle.ActiveRecord框架dll引用,使用NuGut搜索添加.添加对类库Castle.ActiveRecord.DB1.Models,类库Castle.ActiveRecord.DB2.Models的引用。
  • 类库Castle.ActiveRecord.DB1.Models,类库Castle.ActiveRecord.DB2.Models添加Castle.ActiveRecord、NHibernate引用。
  • 技术分享

     4.Castle.ActiveRecord.DB1.Models类库添加DB1ActiveRecordBase抽象类文件,继承自ActiveRecordBase基类.

      添加Post类,继承自DB1ActiveRecordBase抽象类

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 
     7 namespace Castle.ActiveRecord.DB1.Models
     8 {
     9 public abstract class DB1ActiveRecordBase : ActiveRecordBase
    10  {
    11 
    12  }
    13 }
     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 
     7 namespace Castle.ActiveRecord.DB1.Models
     8 {
     9 [ActiveRecord("Post")]
    10 public class Post : DB1ActiveRecordBase
    11  {
    12  /// <summary>
    13  /// 自增主键
    14  /// </summary>
    15  [PrimaryKey(PrimaryKeyType.Identity, Column = "Id")]
    16  public int Id { set; get; }
    17 
    18 
    19  /// <summary>
    20  /// 主题
    21  /// </summary>
    22  [Property("Subject")]
    23  public string Subject { set; get; }
    24 
    25 
    26  /// <summary>
    27  /// 内容
    28  /// </summary>
    29  [Property("Text")]
    30  public string Text { set; get; }
    31 
    32  /// <summary>
    33  /// 添加日期
    34  /// </summary>
    35  [Property("DateAdded")]
    36  public DateTime DateAdded { set; get; }
    37 
    38  public static IEnumerable<Post> FindAllBy()
    39  {
    40  return FindAll(typeof(Post)).Cast<Post>(); ;
    41  }
    42  }
    43 }


    Castle.ActiveRecord.DB2.Models类库添加DB2ActiveRecordBase抽象类文件,继承自ActiveRecordBase基类
    添加Post类,继承自DB2ActiveRecordBase抽象类

     

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 
     7 namespace Castle.ActiveRecord.DB2.Models
     8 {
     9 public abstract class DB2ActiveRecordBase : ActiveRecordBase
    10  {
    11 
    12  }
    13 }
     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 
     7 namespace Castle.ActiveRecord.DB2.Models
     8 {
     9 [ActiveRecord("Post")]
    10 public class Post : DB2ActiveRecordBase
    11  {
    12  /// <summary>
    13  /// 自增主键
    14  /// </summary>
    15  [PrimaryKey(PrimaryKeyType.Identity, Column = "Id")]
    16  public int Id { set; get; }
    17 
    18 
    19  /// <summary>
    20  /// 主题
    21  /// </summary>
    22  [Property("Subject")]
    23  public string Subject { set; get; }
    24 
    25 
    26  /// <summary>
    27  /// 内容
    28  /// </summary>
    29  [Property("Text")]
    30  public string Text { set; get; }
    31 
    32  /// <summary>
    33  /// 添加日期
    34  /// </summary>
    35  [Property("DateAdded")]
    36  public DateTime DateAdded { set; get; }
    37 
    38  public static IEnumerable<Post> FindAllBy()
    39  {
    40  return FindAll(typeof(Post)).Cast<Post>(); ;
    41  }
    42  }
    43 }

    5.MVC项目ActiveRecord.Demo项目Web.config配置多数据库,主要是config节的type的配置

    <configSections>
     <section name="activerecord"
      type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord" />
     </configSections>
    
     <connectionStrings>
     <add name="Castle.ActiveRecord.DB1" connectionString="Data Source=.;Initial Catalog=Castle.ActiveRecord.DB1;Integrated Security=SSPI"/>
     <add name="Castle.ActiveRecord.DB2" connectionString="Data Source=.;Initial Catalog=Castle.ActiveRecord.DB2;Integrated Security=SSPI"/>
     </connectionStrings>
     <activerecord isWeb="true">
     <config type="Castle.ActiveRecord.DB1.Models.DB1ActiveRecordBase,Castle.ActiveRecord.DB1.Models">
     <add key="connection.driver_class" value="NHibernate.Driver.SqlClientDriver" />
     <add key="dialect" value="NHibernate.Dialect.MsSql2005Dialect" />
     <add key="connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
     <add key="connection.connection_string_name" value="Castle.ActiveRecord.DB1" />
     <add key="proxyfactory.factory_class" value="NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle" />
     </config>
     <config type="Castle.ActiveRecord.DB2.Models.DB2ActiveRecordBase,Castle.ActiveRecord.DB2.Models">
     <add key="connection.driver_class" value="NHibernate.Driver.SqlClientDriver" />
     <add key="dialect" value="NHibernate.Dialect.MsSql2005Dialect" />
     <add key="connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
     <add key="connection.connection_string_name" value="Castle.ActiveRecord.DB2" />
     <add key="proxyfactory.factory_class" value="NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle" />
     </config>
     </activerecord>

    技术分享

    6.ActiveRecord.Demo项目Global文件Application_Start()方法中初始化ActiveRecord配置

     1 using Castle.ActiveRecord;
     2 using Castle.ActiveRecord.Framework;
     3 using System;
     4 using System.Collections.Generic;
     5 using System.Linq;
     6 using System.Web;
     7 using System.Web.Mvc;
     8 using System.Web.Optimization;
     9 using System.Web.Routing;
    10 
    11 namespace ActiveRecord.Demo
    12 {
    13 public class MvcApplication : System.Web.HttpApplication
    14  {
    15  protected void Application_Start()
    16  {
    17   AreaRegistration.RegisterAllAreas();
    18   FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    19   RouteConfig.RegisterRoutes(RouteTable.Routes);
    20   BundleConfig.RegisterBundles(BundleTable.Bundles);
    21 
    22   InitActiveRecord();
    23  }
    24 
    25  private void InitActiveRecord()
    26  {
    27  IConfigurationSource source = System.Configuration.ConfigurationManager.GetSection("activerecord") as IConfigurationSource;
    28   ActiveRecordStarter.Initialize(source,
    29   typeof(Castle.ActiveRecord.DB1.Models.DB1ActiveRecordBase),
    30   typeof(Castle.ActiveRecord.DB1.Models.Post),
    31 
    32   typeof(Castle.ActiveRecord.DB2.Models.DB2ActiveRecordBase),
    33   typeof(Castle.ActiveRecord.DB2.Models.Post)
    34   );
    35  }
    36  }
    37 }

    7.配置现在完成,增加控制器视图,进行两个数据库中Post表数据的显示

  • 新增控制器DB1PostController
  •  1 using Castle.ActiveRecord.DB1.Models;
     2 using System;
     3 using System.Collections.Generic;
     4 using System.Linq;
     5 using System.Web;
     6 using System.Web.Mvc;
     7 
     8 namespace ActiveRecord.Demo.Controllers
     9 {
    10 public class DB1PostController : Controller
    11  {
    12  // GET: DB1Post
    13  public ActionResult Index()
    14  {
    15  IEnumerable<Post> post = Post.FindAllBy();
    16 
    17  return View(post);
    18  }
    19  }
    20 }
    对应视图:
     1 @using Castle.ActiveRecord.DB1.Models
     2 @model IEnumerable<Post>
     3 @{
     4  ViewBag.Title = "DB1-Post";
     5 }
     6 
     7 <h2>DB1-Post</h2>
     8 <table class="table">
     9 <thead>
    10  <tr>
    11  <th>主键</th>
    12  <th>主题</th>
    13  <th>内容</th>
    14  <
     var cpro_id = "u6292429";
     
    
    
    
                                            

    热心网友 时间:2022-05-01 12:16

    (1)需要引用的程序集:

    Castle.ActiveRecord.dll
    Castle.Model.dll
    Nullables.dll
    NHibernate.dll
    Castle.DynamicProxy.dll (Curious? Check DynamicProxy)
    Nullables.NHibernate.dll
    log4net.dll
    Iesi.Collections.dll
    (2)一个简单的控制台工程
    (3)数据库

    CREATE TABLE Blogs (
    blog_id int IDENTITY(1, 1) PRIMARY KEY,
    blog_name varchar(50),
    blog_author varchar(50))

    CREATE TABLE Posts (
    post_id int IDENTITY(1, 1) PRIMARY KEY,
    post_title varchar(50),
    post_contents text,
    post_category varchar(50),
    post_blogid int FOREIGN KEY REFERENCES Blogs (blog_id),
    post_created datetime,
    post_published bit
    )

    2、编写Blog 类

    首先让我们编写一个继承于ActiveRecordBase的类Blog 。

    public class Blog : ActiveRecordBase
    {
    }

    接下来你必须使用ActiveRecordAttribute来让Blog 类知道对应数据库的哪个表。注意这件事情,类的名称是Blog ,而数据表的名称是Blogs,如果这两者相同,这个地方可以不特别指定类对应的数据表。

    [ActiveRecord("Blogs")]
    public class Blog : ActiveRecordBase
    {

    }

    接下来让我们为类添加属性并指定主键吧:

    [ActiveRecord("Blogs")]
    public class Blog : ActiveRecordBase
    {
    private int _id;
    [PrimaryKey(PrimaryKeyType.Native, "blog_id")]
    public int Id
    {
    get { return _id; }
    set { _id = value; }
    }
    }

    在这个例子中,主键需要对应到数据表中的blog_id字段。与上面相同,如果数据表中主键名称和属性名称相同的话,这个地方也不需要特别指定对应关系,这会使事情更加简单,例如,如果主键的字段名称也是Id,下面这样就可以了:

    [PrimaryKey]
    public int Id
    {
    get { return _id; }
    set { _id = value; }
    }

    最后让我们来看完成映射关系的类:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using Castle.ActiveRecord;

    namespace ActiveRecord
    {
    [ActiveRecord("Blogs")]
    public class Blog : ActiveRecordBase
    {
    private int _id;
    private String _name;
    private String _author;

    [PrimaryKey(PrimaryKeyType.Identity, "blog_id")]
    public int Id
    {
    get { return _id; }
    set { _id = value; }
    }

    [Property("blog_name")]
    public String Name
    {
    get { return _name; }
    set { _name = value; }
    }

    [Property("blog_author")]
    public String Author
    {
    get { return _author; }
    set { _author = value; }
    }
    /**//// <summary>
    /// 删除所有
    /// </summary>
    public static void DeleteAll()
    {
    DeleteAll( typeof(Blog) );
    }
    /**//// <summary>
    /// 查询所有
    /// </summary>
    /// <returns></returns>
    public static Blog[] FindAll()
    {
    return (Blog[])FindAll(typeof(Blog));
    }
    /**//// <summary>
    /// 根据Id查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public static Blog Find(int id)
    {
    return (Blog)FindByPrimaryKey(typeof(Blog), id);
    }

    }

    }
    我们把类映射到了数据表、字段和主键,代码非常直白。在开始测试之前,我们还必须提供一些配置信息,这些信息包含了数据库联接的一些设置,我们可以使用AppDomain Config文件来保存这些信息,也可以使用硬编码的方式:

    <code>
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    <configSections>
    <section name="activerecord"
    type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord"/>
    </configSections>
    <activerecord>
    <config>
    <add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver" />
    <add key="hibernate.dialect" value="NHibernate.Dialect.MsSql2000Dialect" />
    <add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
    <add key="hibernate.connection.connection_string" value="UID=sa;Password=yourpass;Initial Catalog=test;Data Source=." />
    </config>
    </activerecord>
    </configuration>
    </code>

    或者:

    InPlaceConfigurationSource source = new InPlaceConfigurationSource();
    Hashtable properties = new Hashtable();
    properties.Add("hibernate.connection.driver_class", "NHibernate.Driver.SqlClientDriver");
    properties.Add("hibernate.dialect", "NHibernate.Dialect.MsSql2000Dialect");
    properties.Add("hibernate.connection.provider", "NHibernate.Connection.DriverConnectionProvider");
    properties.Add("hibernate.connection.connection_string", "UID=sa;Password=;Initial Catalog=test;Data Source=.");
    source.Add(typeof(ActiveRecordBase), properties);
    ActiveRecordStarter.Initialize(source, typeof(Blog));

    在这个例子中,我们可以象下面这样初始化:

    IConfigurationSource source = System.Configuration.ConfigurationSettings.GetConfig("activerecord") as IConfigurationSource;
    ActiveRecordStarter.Initialize(source, typeof(Blog));
    现在你能够象下面这样运行程序了:

    //删除所有
    Blog.DeleteAll();
    //添加
    Blog blog = new Blog();
    blog.Name = "ttinfo";
    blog.Author="ttinfo2";
    blog.Save(); // or blog.Create();
    //按照id查询
    Int id=1;
    Blog blog= Blog.Find(id);
    ……
    声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com
    玉米仁子饭产自哪里 中国期货交易所的交易品种有哪些? 历史要怎么读,有啥诀窍 高中历史诀窍 年终会活动策划方案 深度解析:第一财经回放,探索财经新风向 逆水寒手游庄园怎么邀请好友同住 逆水寒手游 逆水寒不同区可以一起组队吗? 逆水寒手游 逆水寒怎么进入好友世界? 逆水寒手游 逆水寒怎么去别人的庄园? 党员为人民服务的事迹 摘录一则当代共产党员全心全意为人民服务的事情 基层党员应该怎样为民服务 党员个人为民办实事清单怎么填 党员可以做什么为民党员为民服务的事- 问一问 教师教师党员为人民做好事服务日记 党员为民服务活动内容 松下洗衣机能够注水而不能蓄水.上面放,下面一直漏.是什么毛病? 滚筒洗衣机不自动脱水 松下滚筒洗衣机不自动进行脱水,然后漂水一直加水是什么原因? 松下洗衣机蓄水和注水什么意思 松下自能洗衣机所有条洗功能都变成了边洗边放水又边注水什么原因? 如何界定分类客户,挽回流失客户的策略与战略怎样进行策划与执行 案例分析 顾客是怎么流失的 挽留有价值的流失客户应采取措施? 老顾客流失如何挽挽回 共享单车行业怎样挽回流失客户及案例 因服务因素而客户流失的案例有哪些 老客户因为价格原因要流失了,该怎么挽回 怎样挽回流失的顾客 网店顾客流失如何挽回? 我有实体花店的,要如何才能在网上接单来做呢? 霍元甲里面的陈真是谁演的? 大侠霍元甲是哪年引进大陆的? 赵倩男谁演的? 梁小龙是不是演大侠霍元甲的?其它电影名字或电视剧名字? 霍元甲扮演者黄元申,最后他选择了出家这是为什么? 写落款时先写日期后写名字,还是先写名字后写日期? 抖音收藏的音乐选使用总显示加载中怎么回事一首爱的奉献怎么老是在加载... 力帆V16S保险管在哪里 力帆v16和力帆v16s机油滤芯是通用的吗? 偏偏爱上你16集,17集在线观看地址? 请问这个公式是什么意思? =SUM(P16,S16,V16,Y16,AB16)/0.8 最新极速版迪优美特s16网络电视机顶盒 鑫卓越v16s4.04 为什么一键root不了 很多软件都试过了 微信群怎么做到发条消息只给单人看见,没被踢,就是群主发的消息自己看得见,别人看不见? 请问路由器怎么安装 装路由器怎么安装 急急。谢谢 路由器怎么安装求高手 家用路由器怎么安装? 苹果11充电线怎么连接电脑