Is the default constructor really necessary for nhibernate to persist an object?

℡╲_俬逩灬. 提交于 2020-02-03 08:05:14

问题


for some reason I don't wanna let user to create an instance of the object, without sending a property to the constructor but as I know the object should have default constructor and so it would be possible to create an instance with out sending requierd property. is there any way to prevent this problem? and if yes does it have any side effect?


回答1:


Just use a protected default constructor:

public class Product
{
    protected Product() { }

    public Product(Category category)
    {
        this.Category = category;
    }
}



回答2:


"NHibernate allows a private default constructor for Value Objects, but for Entities you will need a default public or protected constructor as private is not sufficient."

Here you can find something:

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

Here there's an experiment to work without constructor:

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

This is an example working with Dependency Injection:

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



来源:https://stackoverflow.com/questions/6186032/is-the-default-constructor-really-necessary-for-nhibernate-to-persist-an-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!