Domanda

I read the chapter 10 "read-only entities" in NHibernate Reference Documentation as the following:

http://nhibernate.info/doc/nh/en/index.html#readonly

But unfortunately I DO NOT know why use read-only entities. I think I need some background to understand it, for example:

1. immutable classes means "static" class in C# code? let's use code to display it

public class entity
{
    public virtual int Id {get; }
    public virtual DateTime CreatedTime 
    {
        get; 
        //how about I add this becasue it should be set before session.Save()
        private set; 
    }

}
  1. use the read-only entities for performance reason?(no dirty-check and save memoroy)
  2. read-only entities will not be persisted forever ......

Any explanation is helpful, thanks very much in advance.

È stato utile?

Soluzione

Lets have some clarification to your questions:

1) immutable classes means "static" class in C# code?

No, immutable means, that the object cannot be modified after creation. Meaning all property values cannot be changed. Usually you have to take care about that yourself in your code if and how to make an object immutable. A normal entity with properties having getters and setters are mutable, because you can call the setter... One way would be to have a readonly backing field and all properties of the object are not exposing a setter...

In case of nhibernate, you can map your entity with immutable flag. If you then try to update a property of a loaded instance, nh might throw an exception.

2) use the read-only entities for performance reason?(no dirty-check and save memory)

Yes that's one very good reason.

For example, if you want to display a list of entities somewhere in your application and you know that within the session you load those entities from the database, you will not modify and save them, you can load them as read-only which will let nh optimize it.

3) read-only entities will not be persisted forever ......

Don't know what you mean with this one?! Read-only entities simply mean a read-only representation of what you have in your database. Nh expects the instance to be 100% in sync with the database representation. Any changes/updates to that entity would make it not read-only.

So in general it simply depends on what you need. If you just need read only access to entities within one session, you can use this feature to improve performance. Otherwise, do not use it.

Hope this answers your questions.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top