NHibernate.MappingException映射多个类和表:无法编译映射文档:NHibernateDemo.Order.hbm.xml

时间:2017-08-03 10:22:52

标签: xml nhibernate mapping

当我运行主程序时,它会抛出异常

  

“无法编译映射文档:NHibernateDemo.Order.hbm.xml”   在线:       cfg.AddAssembly(Assembly.GetExecutingAssembly());在里面       ConfigureNHibernate()方法。

请你提一些建议吗?

Below are my implementations

    I have a Customer class that has another class Location which maps to the same table "Customer":

        public class Customer
        {
            public Customer()
            {
                MemberSince = DateTime.UtcNow;
                Orders = new HashSet<Order>();
            }

            public virtual Guid Id { get; set; }
            public virtual string FirstName { get; set; }
            public virtual string LastName { get; set; }
            public virtual double AverageRating { get; set; }
            public virtual int Points { get; set; }

            public virtual bool HasGoldStatus { get; set; }
            public virtual DateTime MemberSince { get; set; }
            public virtual CustomerCreditRating CreditRating { get; set; }
            public virtual Location Address { get; set; }
            public virtual ISet<Order> Orders { get; set; }
            public virtual void AddOrder(Order order) { Orders.Add(order); order.Customer = this; }

            public override string ToString()
            {
                var result = new StringBuilder();

                result.AppendFormat("{1} {2} ({0})\r\n\tPoints: {3}\r\n\tHasGoldStatus:" +
                    "{4}\r\n\tMemberSince: {5} ({7})\r\n\tCreditRating: {6}\r\n\tAverageRating:" +
                    "{8}\r\n", Id, FirstName, LastName, Points, HasGoldStatus, MemberSince,
                    CreditRating, MemberSince, AverageRating);
                result.AppendLine("\tOrders:");

                foreach (var order in Orders)
                {
                    result.AppendLine("\t\t" + order);
                }

                return result.ToString();
            }
            }

        public class Location
        {
            public virtual string Street { get; set; }
            public virtual string City { get; set; }
            public virtual string Province { get; set; }
            public virtual string Country { get; set; }
        }

        public enum CustomerCreditRating
        {
            Excellent,
            VeryVeryGood,
            VeryGood,
            Good,
            Neutral,
            Poor,
            Terrible
        }

The Customer table was created as follows: 

        CREATE TABLE [dbo].[Customer] (
        [Id]            UNIQUEIDENTIFIER NOT NULL,
        [FirstName]     NVARCHAR (100)   NOT NULL,
        [LastName]      NVARCHAR (100)   NOT NULL,
        [Points]        INT              NULL,
        [HasGoldStatus] BIT              NULL,
        [MemberSince]   DATE             NULL,
        [CreditRating]  NCHAR (20)       NULL,
        [AverageRating] DECIMAL (18, 4)  NULL,
        [Street]        NVARCHAR (100)   NULL,
        [City]          NVARCHAR (100)   NULL,
        [Province]      NVARCHAR (100)   NULL,
        [Country]       NVARCHAR (100)   NULL,
        PRIMARY KEY CLUSTERED ([Id] ASC)
    );

CREATE TABLE [dbo].[Order] (
    [Id]         UNIQUEIDENTIFIER NOT NULL,
    [CustomerId] UNIQUEIDENTIFIER NULL,
    [Ordered]    DATETIME         NULL,
    [Shipped]    DATETIME         NULL,
    [Street]     NVARCHAR (100)   NULL,
    [City]       NVARCHAR (100)   NULL,
    [Province]   NVARCHAR (100)   NULL,
    [Country]    NVARCHAR (100)   NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

My Customer configuration xml is as follows: 

<?xml version="1.0" encoding="utf-8" ?>
    <hibernate-mapping mlns ="urn:nhibernate-mapping-2.2" assembly="NHibernateDemo"
          namespace = "NHibernateDemo">
      <class name = "Customer" table="Customer">

        <id name = "Id">
          <generator class= "guid.comb"/>
        </id>

        <property name = "FirstName" />
        <property name = "LastName" />
        <property name = "AverageRating" />
        <property name = "Points" />
        <property name = "HasGoldStatus" />
        <property name = "MemberSince" type="UtcDateTime" />
        <property name = "CreditRating" type="CustomerCreditRatingType" />

        <component name = "Address"> 
          <property name = "Street" />
          <property name = "City" />
          <property name= "Province" />
          <property name = "Country" />
        </component>

        <set name = "Orders" table = "Order" >
          <key column = "CustomerId" />
          <one-to-many class = "Order" /> 
        </set>
      </class>

    </hibernate-mapping>


hibernate configuration xml:

        <?xml version = "1.0" encoding = "utf-8" ?>
      <hibernate-configuration xmlns = "urn:nhibernate-configuration-2.2">

        <session-factory>
          <property name = "connection.connection_string_name">default</property>

          <property name = "connection.driver_class">
            NHibernate.Driver.SqlClientDriver
          </property>

          <property name = "dialect">
            NHibernate.Dialect.MsSql2008Dialect
          </property>

          <property name = "show_sql">true</property>
        </session-factory>

      </hibernate-configuration>


Order class:

         public class Order
        {
            public virtual Guid Id { get; set; }
            public virtual DateTime Ordered { get; set; }
            public virtual DateTime? Shipped { get; set; }
            public virtual Location ShipTo { get; set; }
            public virtual Customer Customer { get; set; }

            public override string ToString()
            {
                return string.Format("Order Id: {0}", Id);
            }

        }

Order xml mapping:

        <?xml version="1.0" encoding="utf-8" ?>
    <hibernate-mapping mlns ="urn:nhibernate-mapping-2.2" assembly="NHibernateDemo"
          namespace = "NHibernateDemo">
      <class name = "Order" table="Order">

        <id name = "Id">
          <generator class= "guid.comb"/>
        </id>

        <property name = "Ordered" />
        <property name = "Shipped" />

        <component name = "ShipTo">
          <property name = "Street" />
          <property name = "City" />
          <property name= "Province" />
          <property name = "Country" />
        </component>

        <many-to-one name="Customer" class="Customer" column="CustomerId" />
      </class>

    </hibernate-mapping>

Main Program 

        class Program
        {
            private static void Main(string[] args)
            {
                var cfg = ConfigureNHibernate();
                var sessionFactory = cfg.BuildSessionFactory();

                Guid id;
                using (var session = sessionFactory.OpenSession())

                using (var tx = session.BeginTransaction())
                {
                    var newCustomer = CreateCustomer();
                    Console.WriteLine("New Customer:");
                    Console.WriteLine(newCustomer);

                    //https://stackoverflow.com/questions/17736067/nhibernate-config-mapping-file
                    //Preventing "No persistor exception" by: 
                    //Set the "Build Action" property of the hbm.xml file to "Embedded Resources"
                    //so that it gets copied to your project working directory during deployment. 
                    session.Save(newCustomer);
                    id = newCustomer.Id;
                    tx.Commit();
                }

                using (var session = sessionFactory.OpenSession())

                using (var tx = session.BeginTransaction())
                {
                    var reloaded = session.Load<Customer>(id);
                    Console.WriteLine("Reloaded:");
                    Console.WriteLine(reloaded);
                    tx.Commit();
                }
                Console.WriteLine("Press <Enter> to exit...");
                Console.ReadLine();
            }

            private static Customer CreateCustomer()
            {
                var customer = new Customer
                {
                    FirstName = "John",
                    LastName = "Doe",
                    Points = 100,
                    HasGoldStatus = true,
                    MemberSince = new DateTime(2012, 1, 1),
                    CreditRating = CustomerCreditRating.Good,
                    AverageRating = 42.42424242,
                    Address = CreateLocation()
                };

                var order1 = new Order
                {
                    Ordered = DateTime.Now
                };

                customer.AddOrder(order1);

                var order2 = new Order
                {
                    Ordered = DateTime.Now.AddDays(-1),
                    Shipped = DateTime.Now,
                    ShipTo = CreateLocation()
                };

                customer.AddOrder(order2);
                return customer;
            }

            private static Location CreateLocation()
            {
                return new Location
                {
                    Street = "123 Somewhere Avenue",
                    City = "Somewhere",
                    Province = "Alberta",
                    Country = "Canada"
                };
            }

            private static Configuration ConfigureNHibernate()
            {
                var cfg = new Configuration();

                cfg.DataBaseIntegration(x =>
                {
                    x.ConnectionStringName = "default";
                    x.Driver<SqlClientDriver>();
                    x.Dialect<MsSql2008Dialect>();
                    x.Timeout = 10; x.BatchSize = 10;
                });

                cfg.SessionFactory().GenerateStatistics();
                cfg.AddAssembly(Assembly.GetExecutingAssembly());
                return cfg;
            }

        }

App.Config中

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

  <connectionStrings>
      <add name="default" connectionString="Data Source=(localdb)\\v11.0;Initial Catalog=NHibernateDemo;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" />
    </connectionStrings>

</configuration>

目的是创建一个新客户和一个订单对象,作为一个集合项目添加到客户,并保存客户对象,以便自动将其写入客户和订单数据库。   该错误似乎与映射到订单表有关。

0 个答案:

没有答案