문제

다음 코드는 Order.OrderItems 속성 (ILIST)이 커밋 될 때 StalestateException 예외를 던집니다. 예외의 전체 텍스트는 다음과 같습니다.

nhibernate.dll에서 'nhibernate.stalestateException'유형의 처리되지 않은 예외

추가 정보 : 예기치 않은 행 카운트 : 0; 예상 : 1

방금 nhibernate를 사용하기 시작했고 이것은 나에게 전혀 의미가 없습니다. 누구든지 무엇이 잘못되었는지 설명 할 수 있습니까?

코드의 대부분은 아래에 추가됩니다. 너무 미안하지만, 나는 그것이 중요한 것을 남기는 것보다 낫다고 생각했습니다.

내가 줄을 댓글을 달면 순서 = 순서입니다, 다른 모든 것은 잘 작동합니다.

using System;
using System.Collections.Generic;
using System.IO;
using AutomappingSample.Domain;
using FluentNHibernate.AutoMap;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace AutomappingSample
{
    class Program
    {
        private const string DbFile = "AutomappingSample.db";
        private const bool useSqlServerCe = true;

        static void Main()
        {
            var factory = CreateSessionFactory();
            using (var session = factory.OpenSession())
            using(var tx = session.BeginTransaction())
            {
                var product1 = new Product
                                   {
                                       Name = "Apples",
                                       UnitPrice = 4.5m,
                                       Discontinued = true
                                   };
                var product2 = new Product
                                   {
                                       Name = "Pears",
                                       UnitPrice = 3.5m,
                                       Discontinued = false
                                   };
                session.Save(product1);
                session.Save(product2);

                var customer = new Customer
                                   {
                                       FirstName = "John",
                                       LastName = "Doe",
                                   };
                session.Save(customer);

                var orderItems = new List<OrderItem>
                                     {
                                         new OrderItem {Id = 1, Quantity = 100, Product = product1},
                                         new OrderItem {Id = 2, Quantity = 200, Product = product2},
                                     };
                var order = new Order()
                                {
                                    Customer = customer, 
                                    Id = 1, 
                                    OrderDate = DateTime.Now, 

                                    // CAUSES FOLLOWING EXCEPTION WHEN COMMIT:
                                    //      An unhandled exception of type 'NHibernate.StaleStateException' 
                                    //      occurred in NHibernate.dll
                                    //
                                    //      Additional information: Unexpected row count: 0; expected: 1
                                    OrderItems = orderItems
                                };
                session.Save(order);

                // EXCEPTION IS THROWN HERE
                tx.Commit();

          }

            Console.WriteLine("Hit enter to exit...");
            Console.ReadLine();
        }

        private static ISessionFactory CreateSessionFactory()
        {
            IPersistenceConfigurer persistenceConfigurer;
            if (useSqlServerCe)
                persistenceConfigurer =
                    MsSqlCeConfiguration.Standard.ConnectionString(c => c.Is("Data Source=AutomappingSample.sdf"));
            else
                persistenceConfigurer = SQLiteConfiguration.Standard.UsingFile(DbFile);

            return Fluently.Configure()
                .Database(persistenceConfigurer)
                .Mappings(m => m.AutoMappings.Add(
                                   AutoPersistenceModel
                                       .MapEntitiesFromAssemblyOf<Customer>()
                                       .WithSetup(s => { s.IsBaseType = type => type == typeof (EntityBase); })
                                       .Where(t => t.Namespace.EndsWith("Domain"))
                                       .ConventionDiscovery.Add<MyStringLengthConvention>()
                                       .ConventionDiscovery.Add<MyIdConvention>()
                                       .ConventionDiscovery.Add<MyForeignKeyConvention>()
                                   ))
                .ExposeConfiguration(BuildSchema)
                .BuildSessionFactory();
        }

        private static void BuildSchema(Configuration config)
        {
            // delete the existing db on each run (only for SQLite)
            if (File.Exists(DbFile))
                File.Delete(DbFile);

            // this NHibernate tool takes a configuration (with mapping info in)
            // and exports a database schema from it
            new SchemaExport(config)
                .Create(true, true);
        }
    }
}

namespace AutomappingSample.Domain
{
    public class EntityBase
    {
        public virtual int Id { get; set; }
    }
}

using System;
using System.Collections.Generic;

namespace AutomappingSample.Domain
{
    public class Order : EntityBase
    {
        public virtual DateTime OrderDate { get; set; }
        public virtual Customer Customer { get; set; }
        public virtual IList<OrderItem> OrderItems { get; set; }
    }
}

namespace AutomappingSample.Domain
{
    public class OrderItem : EntityBase
    {
        public virtual int Quantity { get; set; }
        public virtual Product Product { get; set; }
    }
}
도움이 되었습니까?

해결책 2

질문을 게시 한 이후, 캐스케이드 저축을 얻는 가장 쉬운 방법은 DefaultCASCADE 컨벤션을 추가하십시오.

"var autopersistancemodel = ..."을 시작하는 아래 코드의 섹션을 참조하십시오.

    private static ISessionFactory CreateSessionFactory()
    {
        ISessionFactory sessionFactory = null;

        // Automapped XML files will be exported to project's
        // ...\bin\x86\Debug\AutoMapExport directory
        // See ".ExportTo()" below
        const string autoMapExportDir = "AutoMapExport";
        if( !Directory.Exists(autoMapExportDir) )
            Directory.CreateDirectory(autoMapExportDir);

        try
        {
            var autoPersistenceModel = 
                AutoMap.AssemblyOf<DlsAppOverlordExportRunData>()
                        // Only map entities in the DlsAppAutomapped namespace
                       .Where(t => t.Namespace == "DlsAppAutomapped")
                       // Do cascading saves on all entities so lists 
                       // will be automatically saved 
                       .Conventions.Add( DefaultCascade.All() )
                ;

            sessionFactory = Fluently.Configure()
                .Database(SQLiteConfiguration.Standard
                              .UsingFile(DbFile)
                              // Display generated SQL on Console
                              .ShowSql()
                         )
                .Mappings(m => m.AutoMappings.Add(autoPersistenceModel)
                                             // Save XML mapping files to this dir
                                             .ExportTo(autoMapExportDir)
                         )
                .ExposeConfiguration(BuildSchema)
                .BuildSessionFactory()
                ;
        }
        catch (Exception e)
        {
            Debug.WriteLine(e);
        }

        return sessionFactory;
    }

다른 팁

먼저 저장해야합니다 orderItems 저장을 시도하기 전에 order:

session.Save(orderItems[0]);
session.Save(orderItems[1]);
session.Save(order);

순서대로 주문에 대한 저축을 계단식으로 계단식으로 말해야 할 수도 있습니다.

다음과 같은 것 : (에서 여기)

.Override<Order>(map =>
{
  map.HasMany(x => x.OrderItems)
    .Cascade.All();
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top