我有这样一个类:
public class Account
{
public virtual int Id { get; private set; }
public virtual string Username { get; set; }
[EditorBrowsable( EditorBrowsableState.Never )]
public virtual string Password { get; private set; }
public void SetPassword( string password ){ ... }
public bool CheckPassword( string password ) { ... }
}
我已经这样设置了,因为我不想在使用 Account
类型的代码中直接使用 Password
属性。帐户映射看起来像这样:
public class AccountMap : ClassMap<Account>
{
public AccountMap()
{
Id( x => x.Id );
Map( x => x.Username );
Map( x => x.Password );
}
}
当我实际将它与 NHibernate 一起使用时,我得到一个 InvalidProxyTypeException
NHibernate.InvalidProxyTypeException: The following types may not be used as proxies:
Fringine.Users.Account: method SetPassword should be virtual
Fringine.Users.Account: method CheckPassword should be virtual
我知道 NHibernate 正在尝试创建一个代理类来支持延迟加载,并且我可以将这些方法标记为虚拟,将 Not.LazyLoad() 添加到映射中以解决异常。但是 - 我不想做其中任何一个。我想支持延迟加载,但我不明白为什么这些方法需要是虚拟的。
NHibernate(或内部的 CaSTLe)是否评估方法的内容以确定使用哪些字段并优化这些属性的延迟加载?如果不是,为什么方法需要是虚拟的,如果所有属性都是虚拟的,并且当它们被方法引用时它们将被延迟加载。
有没有办法从虚拟需求中排除某些方法?
最佳答案
原因是您可以访问方法中的字段,这些字段不会被初始化。所以最简单的方法是在对对象的任何调用中加载实体的内容(唯一的异常(exception)是访问 id,它已经在代理中可用)。
因此您可以像没有代理一样安全地实现您的方法 - 权衡方法需要是虚拟的(我同意 - 并不完美)。
如果您认为这是您的类设计的问题,请尝试将功能移至另一个类(例如 PasswordManager、PasswordValidator 等)。此类将聚合 Account 或将其作为参数,因此仅当此类实际调用其属性之一时才会加载 Account。
关于c# - 使用 nHibernate 忽略实体类型的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1120574/