需要帮助Fluent Nhibernate Automapping的'No persister for:'例外

时间:2010-07-27 16:27:49

标签: c# .net nhibernate fluent-nhibernate automapping

我在应用NHibernate Fluent Automapping方面遇到了一些问题。它在测试项目中表现很好。但现在......

Test method [PROJECTNAME].SubscriptionTest.SubscriptionConstructorTest threw exception:  NHibernate.MappingException: No persister for: [PROJECTLIB].SubscriptionManagerRP

该类(然后,同样的异常出现了一个更简单的测试类 - 所以问题不应该在这里):

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "2.0.50727.4927")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://docs.oasis-open.org/wsn/b-2")]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://docs.oasis-open.org/wsn/b-2", IsNullable = false)]
    [System.Runtime.Serialization.DataContractAttribute(Name = "SubscriptionManagerRP", Namespace = "http://docs.oasis-open.org/wsn/b-2")]
    public class SubscriptionManagerRP
    {

        private string id;

        public string Id
        {
            get
            {
                return id;
            }
            set
            {
                id = value;
            }
        }

        public Boolean Save()
        {
            DatabaseAccess access = new DatabaseAccess();
            var sessionFactory = access.getSessionFactory();

            //try
            //{
                using (var session = sessionFactory.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {


                        SaveTextMess(this.ToString());
                        session.Save(this);
                        transaction.Commit();
                        return true;
                    }
                }
            //}
            //catch (Exception e) 
            //{
            //    SaveTextMess("ERROR: " + e);
            //    Console.WriteLine(e); 
            //}

            //SaveTextMess("false");
            return false;
        }

        private void SaveTextMess(String output)
        {
            //Just for Demo purposes, saving text file per message that should be sent

            // create a writer and open the file
            TextWriter tw = new StreamWriter("C:\\Temp\\CespSubscriptionManagerRPMessage.txt");

            // write a line of text to the file
            tw.WriteLine(output);

            // close the stream
            tw.Close();
        }

//###################################




        [EditorBrowsable(EditorBrowsableState.Never)]
        private EndpointReferenceType consumerReferenceField;

        [EditorBrowsable(EditorBrowsableState.Never)]
        private FilterType filterField;

        [EditorBrowsable(EditorBrowsableState.Never)]
        private SubscriptionPolicyType subscriptionPolicyField;

        [EditorBrowsable(EditorBrowsableState.Never)]
        private System.DateTime creationTimeField;

        [EditorBrowsable(EditorBrowsableState.Never)]
        private bool creationTimeFieldSpecified;

        private static System.Xml.Serialization.XmlSerializer serializer;

        /// <summary>
        /// .ctor class constructor
        /// </summary>
        public SubscriptionManagerRP()
        {
            this.subscriptionPolicyField = new SubscriptionPolicyType();
            this.filterField = new FilterType();
            this.consumerReferenceField = new EndpointReferenceType();
        }

        [System.Runtime.Serialization.DataMemberAttribute()]
        public EndpointReferenceType ConsumerReference
        {
            get
            {
                return this.consumerReferenceField;
            }
            set
            {
                this.consumerReferenceField = value;
            }
        }

        [System.Runtime.Serialization.DataMemberAttribute()]
        public FilterType Filter
        {
            get
            {
                return this.filterField;
            }
            set
            {
                this.filterField = value;
            }
        }

        [System.Runtime.Serialization.DataMemberAttribute()]
        public SubscriptionPolicyType SubscriptionPolicy
        {
            get
            {
                return this.subscriptionPolicyField;
            }
            set
            {
                this.subscriptionPolicyField = value;
            }
        }

        [System.Runtime.Serialization.DataMemberAttribute()]
        public System.DateTime CreationTime
        {
            get
            {
                return this.creationTimeField;
            }
            set
            {
                this.creationTimeField = value;
            }
        }

        [System.Xml.Serialization.XmlIgnoreAttribute()]
        [System.Runtime.Serialization.DataMemberAttribute()]
        public bool CreationTimeSpecified
        {
            get
            {
                return this.creationTimeFieldSpecified;
            }
            set
            {
                this.creationTimeFieldSpecified = value;
            }
        }

        private static System.Xml.Serialization.XmlSerializer Serializer
        {
            get
            {
                if ((serializer == null))
                {
                    serializer = new System.Xml.Serialization.XmlSerializer(typeof(SubscriptionManagerRP));
                }
                return serializer;
            }
        }

        #region Serialize/Deserialize
        /// <summary>
        /// Serializes current SubscriptionManagerRP object into an XML document
        /// </summary>
        // <returns>string XML value</returns>
        public virtual string WriteObject()
        {
            System.IO.StreamReader streamReader = null;
            System.IO.MemoryStream memoryStream = null;
            try
            {
                memoryStream = new System.IO.MemoryStream();
                Serializer.Serialize(memoryStream, this);
                memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
                streamReader = new System.IO.StreamReader(memoryStream);
                return streamReader.ReadToEnd();
            }
            finally
            {
                if ((streamReader != null))
                {
                    streamReader.Dispose();
                }
                if ((memoryStream != null))
                {
                    memoryStream.Dispose();
                }
            }
        }

        /// <summary>
        /// Deserializes workflow markup into an SubscriptionManagerRP object
        /// </summary>
        // <param name="xml">string workflow markup to deserialize</param>
        // <param name="obj">Output SubscriptionManagerRP object</param>
        // <param name="exception">output Exception value if deserialize failed</param>
        // <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
        public static bool ReadObject(string xml, out SubscriptionManagerRP obj, out System.Exception exception)
        {
            exception = null;
            obj = default(SubscriptionManagerRP);
            try
            {
                obj = ReadObject(xml);
                return true;
            }
            catch (System.Exception ex)
            {
                exception = ex;
                return false;
            }
        }

        public static bool ReadObject(string xml, out SubscriptionManagerRP obj)
        {
            System.Exception exception = null;
            return ReadObject(xml, out obj, out exception);
        }

        public static SubscriptionManagerRP ReadObject(string xml)
        {
            System.IO.StringReader stringReader = null;
            try
            {
                stringReader = new System.IO.StringReader(xml);
                return ((SubscriptionManagerRP)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
            }
            finally
            {
                if ((stringReader != null))
                {
                    stringReader.Dispose();
                }
            }
        }

        /// <summary>
        /// Serializes current SubscriptionManagerRP object into file
        /// </summary>
        // <param name="fileName">full path of outupt xml file</param>
        // <param name="exception">output Exception value if failed</param>
        // <returns>true if can serialize and save into file; otherwise, false</returns>
        public virtual bool SaveToFile(string fileName, out System.Exception exception)
        {
            exception = null;
            try
            {
                SaveToFile(fileName);
                return true;
            }
            catch (System.Exception e)
            {
                exception = e;
                return false;
            }
        }

        public virtual void SaveToFile(string fileName)
        {
            System.IO.StreamWriter streamWriter = null;
            try
            {
                string xmlString = WriteObject();
                System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName);
                streamWriter = xmlFile.CreateText();
                streamWriter.WriteLine(xmlString);
                streamWriter.Close();
            }
            finally
            {
                if ((streamWriter != null))
                {
                    streamWriter.Dispose();
                }
            }
        }

        /// <summary>
        /// Deserializes workflow markup from file into an SubscriptionManagerRP object
        /// </summary>
        // <param name="xml">string workflow markup to deserialize</param>
        // <param name="obj">Output SubscriptionManagerRP object</param>
        // <param name="exception">output Exception value if deserialize failed</param>
        // <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
        public static bool LoadFromFile(string fileName, out SubscriptionManagerRP obj, out System.Exception exception)
        {
            exception = null;
            obj = default(SubscriptionManagerRP);
            try
            {
                obj = LoadFromFile(fileName);
                return true;
            }
            catch (System.Exception ex)
            {
                exception = ex;
                return false;
            }
        }

        public static bool LoadFromFile(string fileName, out SubscriptionManagerRP obj)
        {
            System.Exception exception = null;
            return LoadFromFile(fileName, out obj, out exception);
        }

        public static SubscriptionManagerRP LoadFromFile(string fileName)
        {
            System.IO.FileStream file = null;
            System.IO.StreamReader sr = null;
            try
            {
                file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
                sr = new System.IO.StreamReader(file);
                string xmlString = sr.ReadToEnd();
                sr.Close();
                file.Close();
                return ReadObject(xmlString);
            }
            finally
            {
                if ((file != null))
                {
                    file.Dispose();
                }
                if ((sr != null))
                {
                    sr.Dispose();
                }
            }
        }
        #endregion

        #region Clone method
        /// <summary>
        /// Create a clone of this SubscriptionManagerRP object
        /// </summary>
        public virtual SubscriptionManagerRP Clone()
        {
            return ((SubscriptionManagerRP)(this.MemberwiseClone()));
        }
        #endregion
    }

上面类中的save方法(在测试项目中工作的简单测试类中看起来相同):

 public Boolean Save()
        {
            DatabaseAccess access = new DatabaseAccess();
            var sessionFactory = access.getSessionFactory();

            //try
            //{
                using (var session = sessionFactory.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {


                        SaveTextMess(this.ToString());
                        session.Save(this);
                        transaction.Commit();
                        return true;
                    }
                }
            //}
            //catch (Exception e) 
            //{
            //    SaveTextMess("ERROR: " + e);
            //    Console.WriteLine(e); 
            //}

            //SaveTextMess("false");
            return false;
        }

我在哪里设置连接字符串和会话工厂:

 class SessionFactoryController
    {

        public SessionFactoryController()
        {

        }

        public ISessionFactory GiveFactory()
        {
            return CreateSessionFactory();
        }

        private static void ReferByteCode(){

            //Just to make sure the ByteCodeCastle is loaded
            ProxyFactory fake = new ProxyFactory();
        }

        private static ISessionFactory CreateSessionFactory()
        {
            ReferByteCode();

            var cfg = new FluentNhibernateConfiguration();

            return Fluently.Configure()
              .Database(
               FluentNHibernate.Cfg.Db.MsSqlConfiguration.MsSql2005
                    .ConnectionString("[SERVER];Database=Pets;User ID=NHibernateTester;Password=[PASSWORD];Trusted_Connection=False;")
              )

              .Mappings(m => 
                  m.AutoMappings
                    .Add(AutoMap.AssemblyOf<SubscriptionManagerRP>(cfg))
                )

              .BuildSessionFactory();
        }

    }

配置:

class NotifyFluentNhibernateConfiguration : DefaultAutomappingConfiguration
    {
        public override bool ShouldMap(Type type)
        {
            return type.Namespace == "System.Xml.XmlAttribute";
        } 
    }

配置是处理'System.Xml.XmlAttribute'的早期映射异常。

如果数据库设置不正确,是否可能出现此错误?我已经完成了测试,我知道一个类可以使用NHibernate Automapping(从另一个项目)测试数据库(与其他项目相同)。我仍然得到相同的例外,但对于'简单'类。

所以这不是班级。

它不是连接字符串,因为它是从另一个工作得很好的项目中复制的。

这不是数据库上的设置(或至少是安全/访问设置)。我假设如果我将表配置错误,它应该给出另一个错误,并且如上所述,当我将其指向另一个项目中的某些东西时,我会得到相同的异常。

我删除了所有内容并重写了一次,只是为了确保我没有做一些小愚蠢的错误。如果是这样,我已经完成了两次。

如上所述,正如您所见。 这段代码非常非常简单。唯一复杂的是类。即使我为一个非常非常简单的类更改它,我也会得到相同的异常。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

如果您的类不在System.Xml.XmlAttribute命名空间中,则不会通过自动映射进行映射。很难相信你的班级在那个名字空间里。如果您想要映射,那么ShouldMap应该为您的类型返回true。