开发者

nhibernate random data from database

开发者 https://www.devze.com 2023-02-15 00:34 出处:网络
IList<Companies> companies = NHibernateSession.CreateCriteria(typeof(Companies)) .AddOrder(new RandomOrder())
    IList<Companies> companies = NHibernateSession.CreateCriteria(typeof(Companies))   
.AddOrder(new RandomOrder())                                
                                    .SetMaxResults(3)
                                    .List<Companies>();


public class RandomOrder : Order
        {
            public RandomOrder() : base("", true) { }
            public override NHibernate.SqlCommand.SqlString ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery)
            {
                return new NHibernat开发者_Python百科e.SqlCommand.SqlString("newid()");
            }
        }

how can i make random data from DB. 3 of them. Code i paste not working very well.


Something like this might work... though it'll require 2 db calls:

public IEnumerable<Company> GetRandomCompanies(int maxSelections)
{
    try
    {
        IList<int> companyIds = _session.CreateCriteria<Company>() // get all available company ids
            .SetProjection(LambdaProjection.Property<Company>(c => c.Id)).List<int>();

        return _session.CreateCriteria<Company>()
            .Add(Restrictions.In(LambdaProjection.Property<Company>(c => c.Id), GetRandomCompanyIds(companyIds.ToList(), maxSelections))) // get 3 random Ids
            .List<Company>();
    }
    catch (Exception xpt)
    {
        ErrorSignal.FromCurrentContext().Raise(xpt);
    }

    return new List<Company>();
}

private List<int> GetRandomCompanyIds(List<int> companyIds, int maxSelections)
{
    List<int> randomIds = new List<int>();

    for (int i = 0; i <= maxSelections; i++)
    {
        // this will get you the same result all day, new next day
        // it might not be what you need, so you could just use a new seed.
        Random rng = new Random(DateTime.Now.DayOfYear);
        randomIds.Add(companyIds[rng.Next(companyIds.Count)]);
    }

    return randomIds;
}

edit: also, I haven't tested this at all so who knows what it'll do! It should be at least on the right track. Maybe there's a way that doesn't require 2 db calls


In Nhibernate you can simply select random rows like so using SQL

var query = "SELECT top 3 * from [Companies] ORDER BY NEWID()";
ISQLQuery qry = session.CreateSQLQuery(query).AddEntity(typeof(Companies));
Companies randomCompanies = qry.List<Companies>();
0

精彩评论

暂无评论...
验证码 换一张
取 消