简体   繁体   中英

Generic Entity for NHibernate

I am trying to write a sort of generic data warehouse using NHibernate but I have run into a couple of issues.

I have a class defined as such:

public class Entity
{
    public Entity() { }
    public Entity (string schemaName) 
    {
        this.SchemaName = schemaName;
    }

    [DataMember]
    public string SchemaName { get; set; }

    [DataMember]
    public Guid Id {
        get { return this.Attributes.ContainsKey("id") ? (Guid)this.Attributes["id"] : Guid.Empty; }  
        set { this.Attributes ["id"] = value; }  
    }

    [DataMember]
    public Dictionary<string, object> Attributes = new Dictionary<string, object>();
}

What i'd like to do is use the Attribute dictionary as the columns for a table and the SchemaName as the table name in SQL. I have a couple of wrapper functions to insert/retrieve/delete but it can only do ~170/second. I would like to improve this by using native NHibernate methods. I could technically generate a class in memory based on the column information and feed that to NHibernate but I don't think that is the best option.

How would I accomplish this? Is there an easier way to do this?

Currently I have something that generates the queries based on information passed in and then execute it by using CreateSqlQuery on the NHibernate session object.

So the answer to this question comes directly from NHibernates documentation, which I found in this post: How to save a dynamic object in nhibernate

The solution comes from Dynamic Models and in which you need to configure the session to handle this.

Entity representation modes can also be set on a per ISession basis:

using (ISession dynamicSession = pocoSession.GetSession(EntityMode.Map))
{
    // Create a customer
    var frank = new Dictionary<string, object>();
    frank["name"] = "Frank";
    dynamicSession.Save("Customer", frank);
    ...
}
// Continue on pocoSession

The other alternative is to setup the session factory to do this for you; however, the documentation is unclear ... or I was too lazy to find it ... on how to achieve this.

Thank you @Radim Köhler for posting the documentation for this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM