Fluit Nhibernate: ошибка времени выполнения учебного пособия: неверное имя объекта - PullRequest
2 голосов
/ 13 февраля 2012

Я попытался запустить пример с сайта поддержки 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 Ответ

1 голос
/ 03 июля 2012

Либо «Store» не существует, либо ваша строка подключения входит в систему с пользователем, который имеет другую схему по умолчанию.Если схема таблицы xyz, то вам необходимо выполнить одно из следующих действий:

  1. Ссылаться на таблицу как xyz.Store
  2. Установить схему по умолчанию в SessionFactoryКонфигурация xyz
  3. Установите сопоставление входа в систему 'xyz'.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...