流利的Nhibernate教程运行时错误:无效的对象名称

时间:2012-02-13 10:30:31

标签: nhibernate runtime fluent

我试图从Fluent Nhibernate支持站点运行一个示例,我没有在控制台应用程序中运行它,而是在MVC 3项目中实现它并且它遇到了错误:System.Data.SqlClient.SqlException:无效的对象名称'存储'。

我的映射看起来像这样:

StoreMap.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using MvcApplication1.Models.Domain;
    using FluentNHibernate.Mapping;

    namespace MvcApplication1.Mappings
    {
        public class StoreMap : ClassMap<Store>
        {
            public StoreMap()
            {
                Table("Store");

                Id(x => x.Id);
                Map(x => x.Name);
                HasMany(x => x.Staff)
                  .Inverse()
                  .Cascade.All();
                HasManyToMany(x => x.Products)
                 .Cascade
                 .All()
                 .Table("StoreProduct");
            }
        }
    }

ProductMap.cs:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using MvcApplication1.Models.Domain;
    using FluentNHibernate.Mapping;

    namespace MvcApplication1.Mappings
    {
        public class ProductMap : ClassMap<Product>
        {
            public ProductMap()
            {
                Id(x => x.Id);
                Map(x => x.Name);
                Map(x => x.Price);
                HasManyToMany(x => x.StoresStockedIn)
                  .Cascade
                  .All()
                  .Inverse()
                  .Table("StoreProduct");
            }
        }
    }

EmployeeMap.cs:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using MvcApplication1.Models.Domain;
    using FluentNHibernate.Mapping;

    namespace MvcApplication1.Mappings
    {
        public class EmployeeMap : ClassMap<Employee>
        {
            public EmployeeMap()
            {

                Id(x => x.Id);
                Map(x => x.FirstName);
                Map(x => x.LastName);
                References(x => x.Store);
            }
        }
    }

Store.cs:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    namespace MvcApplication1.Models.Domain
    {
        public class Store
        {
            public virtual int Id { get; private set; }
            public virtual string Name { get; set; }
            public virtual IList<Product> Products { get; set; }
            public virtual IList<Employee> Staff { get; set; }

            public Store()
            {
                Products = new List<Product>();
                Staff = new List<Employee>();
            }

            public virtual void AddProduct(Product product)
            {
                product.StoresStockedIn.Add(this);
                Products.Add(product);
            }

            public virtual void AddEmployee(Employee employee)
            {
                employee.Store = this;
                Staff.Add(employee);
            }
        }
    }

Employee.cs:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    namespace MvcApplication1.Models.Domain
    {
        public class Employee
        {
            public virtual int Id { get; private set; }
            public virtual string FirstName { get; set; }
            public virtual string LastName { get; set; }
            public virtual Store Store { get; set; }
        }
    }

Product.cs:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    namespace MvcApplication1.Models.Domain
    {
        public class Product
        {
            public virtual int Id { get; private set; }
            public virtual string Name { get; set; }
            public virtual double Price { get; set; }
            public virtual IList<Store> StoresStockedIn { get; private set; }

            public Product()
            {
                StoresStockedIn = new List<Store>();
            }
        }
    }

HomeController.cs:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using MvcApplication1.Models.Domain;
    using NHibernate;
    using NHibernate.Cfg;

    using FluentNHibernate.Cfg;
    using FluentNHibernate.Cfg.Db;
    using NHibernate.Tool.hbm2ddl;

    namespace MvcApplication1.Controllers
    {
        public class HomeController : Controller
        {
            List<string> list;

            public ActionResult Index()
            {
                ViewBag.Message = "Welcome to ASP.NET MVC!";

                showMe();

                return View();
            }

            private void showMe()
            {
                list = new List<string>();

                list.Add("test1");
                list.Add("test2");

                ViewBag.Output = list;

                var sessionFactory = CreateSessionFactory();

                using (var session = sessionFactory.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        // create a couple of Stores each with some Products and Employees
                        var barginBasin = new Store { Name = "Bargin Basin" };
                        var superMart = new Store { Name = "SuperMart" };

                        var potatoes = new Product { Name = "Potatoes", Price = 3.60 };
                        var fish = new Product { Name = "Fish", Price = 4.49 };
                        var milk = new Product { Name = "Milk", Price = 0.79 };
                        var bread = new Product { Name = "Bread", Price = 1.29 };
                        var cheese = new Product { Name = "Cheese", Price = 2.10 };
                        var waffles = new Product { Name = "Waffles", Price = 2.41 };

                        var daisy = new Employee { FirstName = "Daisy", LastName = "Harrison" };
                        var jack = new Employee { FirstName = "Jack", LastName = "Torrance" };
                        var sue = new Employee { FirstName = "Sue", LastName = "Walkters" };
                        var bill = new Employee { FirstName = "Bill", LastName = "Taft" };
                        var joan = new Employee { FirstName = "Joan", LastName = "Pope" };

                        // add products to the stores, there's some crossover in the products in each
                        // store, because the store-product relationship is many-to-many
                        AddProductsToStore(barginBasin, potatoes, fish, milk, bread, cheese);
                        AddProductsToStore(superMart, bread, cheese, waffles);

                        // add employees to the stores, this relationship is a one-to-many, so one
                        // employee can only work at one store at a time
                        AddEmployeesToStore(barginBasin, daisy, jack, sue);
                        AddEmployeesToStore(superMart, bill, joan);

                        // save both stores, this saves everything else via cascading
                        session.SaveOrUpdate(barginBasin);
                        session.SaveOrUpdate(superMart);

                        transaction.Commit();
                    }

                    // retreive all stores and display them
                    using (session.BeginTransaction())
                    {
                        var stores = session.CreateCriteria(typeof(Store))
                          .List<Store>();
                    }

                    Console.ReadKey();
                }

            }

            public static void AddProductsToStore(Store store, params Product[] products)
            {
                foreach (var product in products)
                {
                    store.AddProduct(product);
                }
            }

            public static void AddEmployeesToStore(Store store, params Employee[] employees)
            {
                foreach (var employee in employees)
                {
                    store.AddEmployee(employee);
                }
            }

            private static ISessionFactory CreateSessionFactory()
            {
                return Fluently.Configure()
                   .Database(MsSqlConfiguration
                                .MsSql2008
                                .ConnectionString(db => db
                               .FromAppSetting("testBase_db"))
                   /*  .ShowSql()*/)
                    .Mappings(m => m
                                .FluentMappings.AddFromAssemblyOf<HomeController>()
          /*     .ExportTo(path)*/
                              )

        .ExposeConfiguration(BuildSchema)
                 .ExposeConfiguration((c => c.Properties.Add("hbm2ddl.keywords", "none")))
                  .BuildSessionFactory();
            }

            private static void BuildSchema(Configuration config)
            {
                // this NHibernate tool takes a configuration (with mapping info in)
                // and exports a database schema from it

                new SchemaExport(config)
                .SetOutputFile(@"D:\" + @"schema.sql")
               .Create(true, false);

                // config.Configure();
                //  config.AddAssembly(Assembly.LoadFrom("Restaurants24x7.NhibernateDataAccess.dll"));
                // var update = new SchemaUpdate(config);

                // update.Execute(true, true);

            }

            public ActionResult About()
            {
                return View();
            }
        }
    }

错误发生在以下两行:

                        session.SaveOrUpdate(barginBasin);
                        session.SaveOrUpdate(superMart);

并声称它:

could not insert: [MvcApplication1.Models.Domain.Store][SQL: INSERT INTO 
Store (Name) VALUES (?); select SCOPE_IDENTITY()]

这是一个ADOException。

帮助,请...

1 个答案:

答案 0 :(得分:1)

“存储”不存在,或者您的连接字符串是使用具有不同默认架构的用户登录的。如果表的架构为xyz,则必须执行以下操作之一:

  1. 将表格引用为xyz.Store
  2. SessionFactory配置中的默认架构设置为xyz
  3. 将登录映射设置为'xyz'。