How can the NamedSQLQueryDefinition class be used dynamically as a sql-query equivalent?

前端 未结 2 2026
别那么骄傲
别那么骄傲 2021-01-25 20:34

I need to dynamically add named queries to the NHibernate configuration object. The search engines return few hits referencing NamedSQLQueryDefinition or NamedQueryDefinition. B

2条回答
  •  梦毁少年i
    2021-01-25 21:04

    The AddQueries method would be implemented as follows below to "fix" the Fluent NHibernate lack of Loader support. The trick is to properly set up the INativeSQLQueryReturn[] value to contain the mapping from the table columns to the entity properties. It should mimic the contents of the return element of sql-query in the HBM file where the class (with namespace) and property mappings are defined (see XML below). Thanks to @jimbobmcgee for getting me started in this direction!

    private static void AddQueries(Configuration cfg)
    {
        var namedQuery = new NamedSQLQueryDefinition(
            "exec dbo.pr_GETCustomers @CustomerID=?",
            new INativeSQLQueryReturn[]
                {
                    new NativeSQLQueryRootReturn(
                        "Customers",
                        "VehicleInfo.Entities.Customers",
                        new Dictionary
                            {
                                        {"CustomerID", new[] {"CustomerID"}},
                                        {"CompanyName", new[] {"CompanyName"}}
                        },
                        LockMode.Read)
                },
            new List { "dbo.Customers" },
            true,
            null,
            15,
            1000,
            FlushMode.Auto,
            CacheMode.Normal,
            false,
            "",
            null,
            true);
    
        cfg.NamedSQLQueries.Add("pr_GETCustomers", namedQuery);
        var cust = cfg.GetClassMapping(typeof(Customers));
    
        cust.LoaderName = "pr_GETCustomers";
    }
    

    Sample HBM file that does the same thing:

    
        
            
                
                
            
    
            
                
            
    
            
    
            exec dbo.pr_INSERTCustomers @CompanyName=?, @CustomerID=?
            exec dbo.pr_UPDATECustomers @CompanyName=?, @CustomerID=?
            exec dbo.pr_DELETECustomers @CustomerID=?
        
        
            
                
                
            
            exec dbo.pr_GETCustomers @CustomerID=?
        
    
    

提交回复
热议问题