代码之家  ›  专栏  ›  技术社区  ›  Mike Cole

如何使用Linq to NHibernate执行执行时间查询

  •  0
  • Mike Cole  · 技术社区  · 16 年前

    我正在表中插入一条记录,但我希望能够设置 insert上的SortOrder字段从Category中选择MAX(SortOrder)+1 其中SiteID=@SiteID。最简单的方法是什么?

    以下是我的数据结构:
    类别
    身份证件
    网站ID
    排序顺序

    我使用流利的NHibernate和Linq来NHibernate。谢谢你的帮助!

    1 回复  |  直到 16 年前
        1
  •  1
  •   Tahbaza    16 年前

    好的,这里有两种方法。最简单的可能不涉及NHibernate,因为您使用的是SQL Server。。。您可以在表上创建一个INSERT触发器,如下所示:

    CREATE TRIGGER tgINSCategory ON Category INSTEAD OF INSERT
    AS 
    BEGIN
        SET NOCOUNT ON
    
        INSERT INTO Category (SiteID, Name, SortOrder)
        SELECT SiteID, Name, 
            ISNULL((SELECT MAX(c.SortOrder)
                    FROM Category c INNER JOIN INSERTED i ON c.SiteID = i.SiteID), 0) + 1   
        FROM INSERTED
    END
    

    在第一个场景中,您只需NHibernate将SortOrder列映射为只读(只需在fluent NHibernate类map SortOrder属性上添加一个.ReadOnly()。

    using System;
    using System.Reflection;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using NHibernate;
    
        public class InsertDefaults : EmptyInterceptor {
            private const string CREATED_BY = "CreatedById";
    
            private Hashtable GetInsertLoggablePropertyIndexes(string[] Properties) {
                Hashtable result = new Hashtable();
                for (int i = 0; i < Properties.Length; i++) {
                    if (Properties[i] == CREATED_BY) {
                        result.Add(CREATED_BY, i);
                        break;
                    } 
                }
                return result;
            }
    
            public override bool OnSave(object entity, object id, object[] state, string[] propertyNames, NHibernate.Type.IType[] types) {
                if (entity is IInsertLoggable) {  
                    Hashtable indexes = GetInsertLoggablePropertyIndexes(propertyNames);
                    state[(int)indexes[CREATED_BY]] = currentUser;
                    PropertyInfo createdByProp = entity.GetType().GetProperty(CREATED_BY);
                    if (createdByProp != null)
                        createdByProp.SetValue(entity, currentUser, null);
                }
                return base.OnSave(entity, id, state, propertyNames, types);
            }
        }
    

    在我看来,这种典型的触发器操作应该存在于数据库中,我会选择第一种方法。。。

    推荐文章