nhibernate是否真的需要默认构造函数来持久化对象?

Adr*_*bra 4 nhibernate

出于某种原因,我不想让用户创建对象的实例,而不是向构造函数发送属性,但我知道对象应该有默认构造函数,因此可以创建一个不带发送requierd属性的实例.有什么方法可以防止这个问题吗?若是,是否有任何副作用?

Sun*_*oot 6

只需使用受保护的默认构造函数:

public class Product
{
    protected Product() { }

    public Product(Category category)
    {
        this.Category = category;
    }
}
Run Code Online (Sandbox Code Playgroud)


dan*_*iax 5

"NHibernate允许Value Objects的私有默认构造函数,但对于Entities,你需要一个默认的public或protected构造函数,因为private是不够的."

在这里你可以找到一些东西

https://github.com/davybrion/companysite-dotnet/blob/master/content/blog/2009-10-why-nhibernate-entities-need-a-public-or-protected-parameterless-constructor.md

这里有一个没有构造函数的实验:

http://kozmic.net/2011/03/20/working-with-nhibernate-without-default-constructors/

这是一个使用依赖注入的示例:

http://nhibernate.info/blog/2008/12/12/entities-behavior-injection.html