NHibernate非静态方法需要目标错误信息解决方案
我从 NHibernate 收到以下错误消息。我搜索并没有找到该错误的明确解决方案。我偶然发现了一个解决方案并认为我会分享。我的问题原来是我需要为该类定义一个默认构造函数(不接受参数的构造函数):
public class Staff : Entity, IStaff
{
public virtual int StaffId { get; set; }
protected virtual internal Case Case { get; set; }
protected virtual internal Person Person { get; set; }
protected Staff() {} // Define this constructor for NHibernate
public Staff(Person person)
{
Person = person;
}
}
回想起来,当我将构造函数添加到接受 Person 参数的类时,我的问题就开始了。 C# 定义了默认构造函数,但仅当您未定义任何构造函数时才有效。定义构造函数后,您必须显式定义默认构造函数:
如果类没有有构造函数,则会自动生成默认构造函数,并使用默认值来初始化对象字段。 http://msdn.microsoft.com/en-us/library/k6sa6h87.aspx
我发现这一点是因为我有一个类似的类可以工作,并且我已经为该类定义了一个默认构造函数,因为我需要一个在代码中没有参数的构造函数。
错误堆栈跟踪:
System.Reflection.TargetException occurred
Message=**Non-static method requires a target**...
Source=mscorlib
NHibernate.PropertyAccessException occurred
Message=**could not set a property value by reflection setter** of
*YourClassPropertyNameHere* ...
Source=NHibernate
StackTrace:
at NHibernate.Properties.BasicPropertyAccessor.BasicSetter.Set(Object target, Object value)
I was getting this error message below from NHibernate. I searched and did not find a clear solution to this error. I stumbled upon a solution and thought I would share. My problem turned out to be I needed to define a default constructor for the class (one that accepts no parameters):
public class Staff : Entity, IStaff
{
public virtual int StaffId { get; set; }
protected virtual internal Case Case { get; set; }
protected virtual internal Person Person { get; set; }
protected Staff() {} // Define this constructor for NHibernate
public Staff(Person person)
{
Person = person;
}
}
Looking back, my problem started when I added the constructor to the class that accepted a Person parameter. C# defines a default constructor, but only when you do not define any constructors. Once you define a constructor you have to explicitly define the default constructor:
If a class does not have a constructor, a default constructor is automatically generated and default values are used to initialize the object fields.
http://msdn.microsoft.com/en-us/library/k6sa6h87.aspx
I discovered this because I had a similar class that worked and I had defined a default constructor for that one because I needed one with no parameters in my code.
Error Stack Trace:
System.Reflection.TargetException occurred
Message=**Non-static method requires a target**...
Source=mscorlib
NHibernate.PropertyAccessException occurred
Message=**could not set a property value by reflection setter** of
*YourClassPropertyNameHere* ...
Source=NHibernate
StackTrace:
at NHibernate.Properties.BasicPropertyAccessor.BasicSetter.Set(Object target, Object value)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论