How can I do this in nHibernate using queryover :
SELECT MIN(t.subid)+1 AS NextID
FROM subject t
WHERE NOT EXISTS
(SELECT id FROM subject n WHERE n.subid=t.subid+1)
Currently I have this but its not working because of this statement "SubId+1"
_session.QueryOver(() => subject)
.WithSubquery
.WhereNotExists(
subject
.Where(x => x.SubId==SubId+1)
.Select(x => x.Id)
)
.Select(Projections.ProjectionList()
.Add(Projections.Min<subject>(x => x.SubId)))
.List().First()
One way, using NOT IN instead of NOT EXISTS (results are the same) would be like this (the SQL query would be a bit different, but result will be the same)
Subjectsubject = null;
Subjectinner = null;
var subquery = QueryOver.Of<Subject>(() => inner)
.Select(Projections.SqlProjection(
// important the subid is the column name, not property name
" subid - 1 as innerId" // the trick here is, that we compare
, new[] { "innerId" } // inner ID - 1, with outer ID
, new IType[] { NHibernateUtil.Int32 }))
;
var id = session.QueryOver(() => subject)
.WithSubquery
.WhereProperty(() => subject.ID)
.NotIn(subquery)
.Select(Projections.ProjectionList().Add(Projections.Min<Subject>(s => s.ID)))
.SingleOrDefault<int>();
var id = id + 1 ; // here we increment in C#, instead of projecting that into SQL
Summary: not sure about algorithm you've used, but the trick how to get "subid - 1" is to use projection:
Projections.SqlProjection(
" subid - 1 as innerId" // sql statement
, new[] { "innerId" } // its alias
, new IType[] { NHibernateUtil.Int32 }) // type is int
NOTE: I would expect the last Projections to be MAX
Related
I have a function as below :
IEnumerable<Group> GetAllChildren(int parentID)
{
using (Entities db = new Entities())
{
var result = (from x in db.Groups
where x.ParentID == parentID
select x).ToList();
foreach (Group child in result.ToList())
{
result.AddRange(GetAllChildren(child.GroupID));
}
return result;
}
}
In the above function if I pass a group name I get all the children at all levels.
It works as expected.
Now my query looks like something like :
GroupNamesWithCorrespondingEffects
= new ObservableCollection<GroupNameWithCorrespondingEffect>
(from g in db.Groups
select new GroupNameWithCorrespondingEffect
{
GroupID = g.GroupID,
GroupName = g.GroupName,
CorrespondingEffect = g.Master_Effects.Effect
}
);
The above query will give me all the groups.
Now I want to remove all the groups from GroupNamesWithCorrespondingEffects that are children of a group with id == 25.
I have tried .Remove(GetAllChildren(25)) in 2nd query. but I get following error.
Collection.Remove(GroupNameWithCorrespondingEffect) has some invalid arguments.
hope this help you:
var childs = GetAllChildren(25).ToList();
var childIDList = childs.select(u => u.GroupID).ToList();
GroupNamesWithCorrespondingEffects = GroupNamesWithCorrespondingEffects
.Where(u => !childIDList.Contains(u.GroupID)).ToList();
I have a Table(Send) with columns(Id, UserId,SendDate) and another table(Receive) with columns(Id,SendId,UserName).
I want show all records in SendTable with all RecieveUserName.
for example.
(Send)
1 1 2013
2 2 2013
(Recieve)
1 1 Jack
2 1 Ema
3 2 Alex
4 2 Sara
Result
1 1 2013 Jack, Ema
2 2 2013 Alex, Sara
I use this query in SqlServer (The DISTINCT keyword eliminates duplicate rows from the results of a SELECT statement)
SELECT DISTINCT c2.Id,
(SELECT STR( UserName )+ ','
FROM dbo.Reciver c1
WHERE c1.SendId = c2.id FOR XML PATH('')) Concatenated, c2.SendDate, c2.UserId
FROM dbo.Send AS c2 INNER JOIN
dbo.Reciver ON c2.Id = dbo.Reciver.SendId
How do this query in Linq?
Distinct is also available in LINQ.
For example
public class Product
{
public string Name { get; set; }
public int Code { get; set; }
}
Product[] products = { new Product { Name = "apple", Code = 9 },
new Product { Name = "orange", Code = 4 },
new Product { Name = "apple", Code = 10 },
new Product { Name = "lemon", Code = 9 } };
var lstDistProduct = products.Distinct();
foreach (Product p in list1)
{
Console.WriteLine(p.Code + " : " + p.Name);
}
Will return all rows.
var list1 = products.DistinctBy(x=> x.Code);
foreach (Product p in list1)
{
Console.WriteLine(p.Code + " : " + p.Name);
}
will return 9 and 4
It doesn't seem to me that you need to use Distinct in this Linq query. Assuming you have the relationships between tables set up on your linq datacontext, you can do something like this:
var result = from s in context.Send
select new {
id = s.Id,
userId = s.UserId,
date = s.SendDate,
users = s.Receive.Select(u => u.UserName)
}
Note: users will an IEnumerable<String> - you can use string.Join() on the client to join the names into a string.
Update
To return users as a string to first need to 'switch' to Linq To Objects by calling AsEnumerable() or ToList() and the Linq to Sql query.
var output = from s in result.AsEnumerable()
select new {
id = s.id,
userId = s.userId,
date = s.date,
users = string.Join(", ", s.users)
}
Also see Gert Arnolds answer for a good explanation.
What you want can only be done in two steps. Not because of the DISTINCT, but because of the FOR XML. The C# equivalent of the latter is String.Join(), but you can't use that in a linq to entities statement directly. So you must collect the required data first, then switch to linq to objects (by applying AsEnumerable) and then do the concatenation and distinct:
db.Sends
.Where(s => s.Receivers.Any())
.Select(s => new {
s.Id,
Concatenated = s.Receivers.Select(r => r.UserName)
s.SendDate,
s.UserId
})
.AsEnumerable()
.Select(x => new {
s.Id,
Concatenated = String.Join(", ", x.Concatenated)
s.SendDate,
s.UserId
})
.Distinct()
I have a query by QueryOver In Nhibernate 3.1
var q = SessionInstance.QueryOver<Person>()
.Where(p => p.Code == code);
.Select(p => p.Name,p => p.Code);
return q.SingleOrDefault();
This query without select is correct, but with select has a runtime error by this message: Unable to cast object of type 'System.String' to type 'MyNameSpace.Domain.Entities.Person'. How can i select some field of Person?
you need to tell NHibernate explicitly what is the type of your return data since you choose to select some specific properties of your original entity p.Name,P.Code these properties must by returned as of a new type of entity so the new type would be a new object
var query = SessionInstance.QueryOver<Person>()
.Where(p => p.Code == code)
.Select(
p => p.Name,
p => p.Code
)
.List<object>();
this will solve your problem
or if you defined a new entity to hold the new return data as following :
public newPeople
{
public Id { get; set; }
public Nam { get; set; }
}
you can write it like that:
var query = SessionInstance.QueryOver<Person>()
.Where(p => p.Code == code)
.Select(
p => p.Name,
p => p.Code
)
.Select( list =>
new newPeople()
{
Id = (int) list[0],
Name = (string) list[1]
})
.ToList<newPeople>();
I want to do this:
NHibernate.IQueryOver<DataAccess.Domain.Product, DataAccess.Domain.Product> query = session.QueryOver<DataAccess.Domain.Product>();
query = query.Where(x => x.Name == "X");
query = query.Take(1).Skip(3);
List<Product> results = query.List().ToList();
I cant find any help on Skip or Take. The tooltip help (yes I'm that desperate) says that Skip and Take return IQueryOver but the error message says something to the effect "Cant implicitly convert IQueryOver{T} to IQueryOver{T,T}. I don't know what IQueryOver{T,T} is. I didn't ask for one of those anyway.
Try to change your code like this:
NHibernate.IQueryOver<DataAccess.Domain.Product> query = session.QueryOver<DataAccess.Domain.Product>();
query = query.Where(x => x.Name == "X");
query = query.Take(1).Skip(3);
var results = query.List();
Or, even better:
var results = session.QueryOver<DataAccess.Domain.Product>()
.Where(x => x.Name == "X")
.Take(1)
.Skip(3)
.List();
You can check my code here downloading NHibernateQueryOver.
UPDATE:
I think you're missing something. I would suggest you to read this article which has been really helpful for me.
In the paragraph about Associations they say:
An IQueryOver has two types of interest; the root type (the type of entity that the query returns), and the type of the 'current' entity
being queried. For example, the following query uses a join to create
a sub-QueryOver (analagous to creating sub-criteria in the ICriteria
API):
IQueryOver<Cat,Kitten> catQuery =
session.QueryOver<Cat>()
.JoinQueryOver(c => c.Kittens)
.Where(k => k.Name == "Tiddles");
The JoinQueryOver returns a new instance of the IQueryOver than has
its root at the Kittens collection. The default type for restrictions
is now Kitten (restricting on the name 'Tiddles' in the above
example), while calling .List() will return an IList. The type
IQueryOver inherits from IQueryOver.
This is what I do when I want to build multiple filter:
Domain.OrderAddress addressDestination = null;
Domain.Customer customer = null;
Domain.TermsConditionsOfSale termsConditionsOfSale = null;
ICriterion filter1 = Restrictions.Where<Domain.Order>(t => t.Company == "MYCOMPANY");
ICriterion filter2 = Restrictions.Where<Domain.Order>(t => t.WareHouseDelivery == "DEPXX");
ICriterion filter3 = Restrictions.Where<Domain.Order>(t => t.Status == "X");
ICriterion filter4 = Restrictions.Where(() => addressDestination.AddressType == "99");
ICriterion filter5 = Restrictions.Where(() => addressDestination.Province.IsIn(new string[] { "AA", "BB", "CC" }));
ICriterion filter6 = Restrictions.Where(() => termsConditionsOfSale.ReturnedGoodsCode != "01");
var ordersForProvinces = session.QueryOver<Domain.Order>()
.Inner.JoinAlias(t => t.OrderAddresses, () => addressDestination)
.Inner.JoinAlias(t => t.Customer, () => customer)
.Left.JoinAlias(t => t.TermsConditionsOfSale, () => termsConditionsOfSale);
ordersForProvinces
.Where(filter1)
.And(filter2)
.And(filter3)
.And(filter4)
.And(filter5)
.And(filter6);
var Results = ordersForProvinces.Skip(50).Take(20).List();
UPDATE-UPDATE:
NHibernate.IQueryOver<Domain.Person> person = session.QueryOver<Domain.Person>();
var myList = DoSomething(person);
Method:
private static IList<Domain.Person> DoSomething(NHibernate.IQueryOver<Domain.Person> persons)
{
ICriterion filter1 = Restrictions.Where<Domain.Person>(t => t.CompanyName.IsLike("Customer%"));
persons.RootCriteria.Add(filter1);
var x = persons.Skip(1).Take(3).List();
return (x);
}
I want to get an object from my database but only populate it with the unique id identifier. I want all other fields to be null...any ideas on how to approach this????
Using NHibernate Linq provider:
Person obj = session.Query<Person>()
.Where(x => x.Id == id)
.Select(x => new Person() { Id = x.Id } )
.SingleOrDefault();