database - 我应该如何编写我的连接字符串?

标签 database nhibernate orm nhibernate-mapping

我是 Nhibernate 的新手。我已经使用 NuGet 安装了 NHibernate。

NHibernate 的教程很多,但是大部分都非常老(都是用Microsoft VS 2008 提供的)。来自TutorialsPoint的除外.因此,我尝试逐步遵循本教程。这是我的 Program.cs:

  class Program
        {
            static void Main(string[] args)
            {
                var cfg = new Configuration();
                String DataSource = "(localdb)\\MSSQLLocalDB";
                String InitialCatalog = "TutorialsPointDb";
                String IntegratedSecurity = "True";
                String ConnectTimeout = "30";
                String Encrypt = "False";
                String TrustServerCertificate = "False";
                String ApplicationIntent = "ReadWrite";
                String MultiSubnetFailover = "False";

                cfg.DataBaseIntegration(x =>
                {
                    x.ConnectionString = DataSource + InitialCatalog + IntegratedSecurity + ConnectTimeout + Encrypt +
                                         TrustServerCertificate + ApplicationIntent + MultiSubnetFailover;
                    x.Driver<SqlClientDriver>();
                    x.Dialect<MsSql2008Dialect>();
                });

                cfg.AddAssembly(Assembly.GetExecutingAssembly());

                var sefact = cfg.BuildSessionFactory();

                using (var session = sefact.OpenSession())
                {
                    using (var tx = session.BeginTransaction())
                    {
                        var student1 = new Student
                        {
                            ID = 1,
                            FirstMidName = "Allan",
                            LastName = "Bommer"
                        };

                        var student2 = new Student
                        {
                            ID = 2,
                            FirstMidName = "Jerry",
                            LastName = "Lewis"
                        };

                        session.Save(student1);
                        session.Save(student2);

                        tx.Commit();
                    }
                    Console.ReadLine();
                }
            }
        }

我刚刚引用的这些代码与tutorialspoint的教程几乎相同(解决方案名称不同)。我有这个异常(exception):

System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0

从这一行:var sefact = cfg.BuildSessionFactory(); 经过研究,据我了解,此异常是由错误的 ConnectionString 引起的。但是我的 x.ConnectionString 与指令完全相同,我不明白我错过了什么。

我知道通常会有一个数据名称:hibernate.cfg.xml 在具有以下设置的解决方案中:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
  <session-factory>
    <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
    <property name="connection.connection_string">Data Source=localdb\mssqllocaldb;Initial Catalog=TutorialsPointDb</property>
    <property name="show_sql">false</property>
    <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
    <mapping assembly="DataTransfer"/>
  </session-factory> 
</hibernate-configuration>

但不在此步骤中:从 NHibernate 创建数据 - 基本 CRUD 操作部分。 所以我的问题是,我错过了什么?我该如何解决这个异常?

感谢阅读。

我得到的其他异常:

Exception thrown: 'System.IO.FileNotFoundException' in mscorlib.dll

Exception thrown: 'System.ArgumentException' in System.Data.dll

Exception thrown: 'System.ArgumentException' in NHibernate.dll

An unhandled exception of type 'System.ArgumentException' occurred in NHibernate.dll


如果您想自己检查,我项目中的其他代码。 我的数据库:

CREATE TABLE [dbo].[Student]
(
    [ID] INT NOT NULL PRIMARY KEY IDENTITY, 
    [LastName] NVARCHAR(MAX) NULL, 
    [FirstMidName] NVARCHAR(MAX) NULL
)

这是我的一个类Student.cs

   namespace TutorialsPoint
    {
        public class Student
        {
            public virtual int ID { get; set; }
            public virtual string LastName { get; set; }
            public virtual string FirstMidName { get; set; }
        }
    }    

及其Student.hbm.xml文件

  <?xml version = "1.0" encoding = "utf-8" ?> 

<hibernate-mapping xmlns = "urn:nhibernate-mapping-2.2" 
                                     assembly = "TutorialsPoint" namespace = "TutorialsPoint">

    <class name = "Student"> 
        <id name = "ID">
            <generator class = "native"/> 
        </id> 
        <property name = "LastName"/> 
        <property name = "FirstMidName"/> 
    </class> 

</hibernate-mapping>

最佳答案

异常

System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0

相关语句:

...But my x.ConnectionString is just identical with the instruction and I can not understand that what did I miss...

因为,代码正在声明参数:

String DataSource = "(localdb)\\MSSQLLocalDB";
String InitialCatalog = "TutorialsPointDb";
String IntegratedSecurity = "True";
...

不能只是串联

x.ConnectionString = DataSource + InitialCatalog 
     + IntegratedSecurity + ConnectTimeout 
     + Encrypt + ...

因为那会导致结果:

"(localdb)\\MSSQLLocalDBTutorialsPointDbTrue...

但是我们需要这样的东西:

x.ConnectionString = $"DataSource={DataSource};"
    + $"InitialCatalog={InitialCatalog};"
    + $"IntegratedSecurity={IntegratedSecurity}"
    + ...

得到

"DataSource=(localdb)\\MSSQLLocalDB;InitialCatalog=TutorialsPointDb;..

这将导致预期的连接字符串格式:

key1=value1;key2=value2;key3=value3;...

关于database - 我应该如何编写我的连接字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50289618/

相关文章:

c# - 流利的 nhibernate 的分页问题

node.js - Sails.js 中的密码确认和外部模型验证

mysql - 对两个表中的值进行一些计算并将其存储在第三个表mysql中

java - GWT 的 MSI 文件,包括。数据库和Tomcat?

android - 如何在不使用主键时进行插入或替换

c# - Nhibernate HQL SQL Server 2005/2008 包含稳定

c# - 在 NHibernate 中调用 Session.CreateSQLQuery ExecuteUpdate 失败

c# - 我可以传入 T.Property 吗?另外,改进这种方法的想法?

PeeWee 之上的 Python 数据抽象

database - 像 Postgres 模式一样的 Oracle 数据库 : Group tables in folders,?