I'm trying to add a mapping to the table IdentityGroup which has ManyToMany IdentityUsers thought the table IdentityGroupIdentitiy. However when I add the mapping. The result seems to be a something like a cross join.
Expected result for a group with two users:
Group 1:
User 1
User 2
Current result for a group with two users:
Group 1:
User 1
User 2
Group 1:
User 1
User 2
My mapping looks like this:
mapping.HasManyToMany<IdentityUser>(x => x.Users)
.Table("IdentityGroupIdentity")
.ParentKeyColumn("identityGroup_cid")
.ChildKeyColumn("identity_cid");
Code to fetch the data:
public IQueryable<T> Find<T>(params string[] propertiesToLoad)
{
var query = session.Linq<T>();
foreach (var propName in propertiesToLoad)
query.Expand(propName);
if (typeof(T) is ISoftDeletable)
query.Where(x => !(x as ISoftDeletable).IsDeleted);
return query;
}
[...]
public IQueryable<IdentityGroup> Groups
{
get { return Find<IdentityGroup>(new string[] { "DefaultOrganization", "DefaultLocation", "Users" }); }
}
Ant ideas?
Resolved by not "Expanding" the Users-property when fetching...
Related
Normally in SQL we can write this query UPDATE users SET isAdult = 1 WHERE age >18
I want to apply some edit to all rows that satisfy some condition in entity framework core.
I wrote this code and I got an error
List<User> usersList = _context.Users.Where(u => u.age >18).ToList();
usersList.ForEach(a =>
{
a.isAdult = 1;
});
_context.Entry(usersList).State = EntityState.Modified;
_context.SaveChanges();
The error is
System.InvalidOperationException: The entity type 'List' was not
found. Ensure that the entity type has been added to the model. at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.GetOrCreateEntry(Object
entity) at
Microsoft.EntityFrameworkCore.DbContext.EntryWithoutDetectChanges[TEntity](TEntity
entity) at
Microsoft.EntityFrameworkCore.DbContext.Entry[TEntity](TEntity entity)
I made this update but I want to know if this is the best way.
List<Users> usersList = _context.Users.Where(u => u.age >18).ToList();
usersList.ForEach(a =>
{
a.isAdult = 1;
_context.Entry(a).State = EntityState.Modified;
_context.SaveChanges();
});
The error was because the list isn't defined as an EF Entity.
In the end, you don't need to modify the state youself.
List<User> usersList = _context.Users.Where(u => u.age >18).ToList();
usersList.ForEach(a => { a.isAdult = 1; });
_context.SaveChanges();
I need an nhibernate query to get the quantity count .
here's my entities. I have a master Inventory table and a Used Inventory table.
public Inventory
{
Id,
Name,
Type,
...
}
public UsedInventory
{
Id,
Inventory,
Quantity,
Date,
..
}
I am looking for output that look like:
public ResultDTO
{
Inventory,
TotalUsedQuantity
}
please help.
Thanks
In LINQ, it is easy:
session.Query<UsedInventory>().GroupBy(x => x.Inventory).Select(x => new ResultDTO { Inventory = x.Key, TotalUsedQuantity = x.Count() }).ToList();
In QueryOver:
ResultDTO dto = null;
var rrr = session.QueryOver<UsedInventory>().SelectList(list => list
.SelectGroup(m => m.Inventory).WithAlias(() => dto.Inventory)
.SelectCount(m => m.Id).WithAlias(() => dto.TotalUsedQuantity)).List<ResultDTO>();
I have a pretty simple query I'm trying to convert to NHibernate's QueryOver syntax, but I'm having difficulty. The original SQL query is functionally the same as:
SELECT [Post].*, (
SELECT Count(*)
FROM [Comment]
WHERE [Comment].[PostId] = [Post].[Id]) AS [CommentCount]
FROM [Post]
The problem is I'm having difficulty converting this to QueryOver syntax. I tried defining a summary class containing both the Post and the CommandCount as such:
public class PostSummary
{
public Post Post { get; set; }
public CommentCount { get; set; }
}
And then defining the query with a couple of selects:
Post lPostAlias = null;
Comment lCommentAlias = null;
var lCommentSubquery = QueryOver.Of(() => lCommentAlias)
.Where(() => lCommentAlias.Post.Id == lPostAlias.Id)
.ToRowCountQuery();
PostSummary lPostSummaryAlias = null;
session.QueryOver(() => lPostAlias)
.SelectList(list => list
.Select(x => x).WithAlias(() => lSummary.Post)
.SelectSubQuery(lCommentSubQuery).WithAlias(() => lSummary.CommentCount)
.List<PostSummary>();
An exception gets thrown with the error message:
could not resolve property: of: Project.Models.Post
So it looks like it doesn't like the .Select(x => x) part of the query. I was hoping to find something along the lines of 'Projections.RootEntity()` but alas there is no such thing that I can find.
Can someone explain what I'm doing wrong and guide me to the proper way to do this basic query? I imaging I could select all the properties of Post that I want, but worry that I'll lose the ability to take advantage of the proxy sub-classes NHibernate generates for lazy-loading purposes and is not what I want.
using the LINQ provider you can write
var query = from post in session.Query<Post>()
select new PostSummary { Post = post, CommentCount = post.Comments.Count };
return query.ToList();
In my database I have a list of cases:
{ Id: 1, Owner: "guid1", Text: "Question1" }
{ Id: 2, Owner: "guid1", Text: "Question2" }
{ Id: 3, Owner: "guid2", Text: "Question3" }
When querying for data I would also like to have (in my index, result) number of cases each Owner has. So I created a map/reduce index on this collection:
public class RelatedCases
{
public Guid Owner { get; set; }
public int Count { get; set; }
}
public class RelatedCaseIndex : AbstractMultiMapIndexCreationTask<RelatedCases>
{
public RelatedCaseIndex()
{
AddMap<CaseDocument> (c => c.Select(a => new { a.Owner, Count = 1 }));
Reduce = result => result
.GroupBy(a => a.Owner)
.Select(a => new
{
Owner = a.Key,
Count = a.Sum(b => b.Count)
});
}
}
Now I just have no idea how to produce a query to include the data from the index. Based on documentation I tried something like:
session.Query<CaseDocument>().Customize(a => a.Include ...)
or TransformResults on a CaseIndex, which didn't work out properly.
I know I could just requery raven to get me list of all RelatedCases in a separate query, but I would like to do it in one round-trip.
You can't query for Cases and join the result with the map/reduce index on the fly. That's just not how it works, because every query will run against an index, so what you are really asking is joining two indexes. This is something you need to do upfront.
In other words - put all the information you want to query upon into your map/reduce index. You can then run the query on this index and .Include() the documents that you are also interested in.
I dont think you need a MultiMap index, a simple MapReduce index will suffice for this.
You can then query it like so:
session.Query<RelatedCases, RelatedCaseIndex>();
This will bring back a list of RelatedCases with the owner and count.
I have this problem:
When I try to implement Ayende's complex searching found at:
http://ayende.com/Blog/archive/2006/12/07/ComplexSearchingQueryingWithNHibernate.aspx
with the object graph:
Person:
M:1 Address:
M:1 Street:
M:1 Place:
M:1
Country
I get the following error: NHibernate.QueryException: Cannot use
subqueries on a criteria without a projection.
I am doing this:
public List<Person> Find()
{
DetachedCriteria query = DetachedCriteria.For<Person>();
AddAddressQuery(query);
return personRepository.Find(query);
}
private void AddAddressQuery(DetachedCriteria query)
{
DetachedCriteria addressQuery = null;
if (!String.IsNullOrEmpty(SearchParams.HouseNumer))
{
addresaQuery = DetachedCriteria.For<Address>();
addresaQuery.Add(Restrictions.Eq("HouseNumer",
SearchParams.HouseNumer));
}
this.AddStreetQuery(ref addressQuery);
if (addressQuery != null)
{
query.CreateCriteria("Address1",
"address1").Add(Subqueries.Exists(addressQuery));
}
}
private void AddStreetQuery(ref DetachedCriteria query)
{
DetachedCriteria streetQuery = null;
if (this.SearchParams.StreetId.HasValue)
{
streetQuery = DetachedCriteria.For<Street>();
streetQuery .Add( Restrictions.Eq("Id",
this.SearchParams.StreetId.Value));
}
if (streetQuery != null)
{
query = query ?? Query.CreateCriteria("Address1");
query.CreateCriteria("Street",
"street").Add(Subqueries.Exists(streetQuery ));
}
}
What Am I doing wrong?
Please help
Just like the error message - you need to set a projection for any subqueries.
Your variable addressQuery, a DetachedCriteria, is used as a subquery, but it doesn't have a projection. The relevant portion of the query, when converted to SQL, would look like this:
... EXISTS(SELECT FROM Address WHERE HouseNumber = #HouseNumber)
... which is invalid SQL because no columns (a.k.a projections) have been specified in the select clause.
Use SetProjection to specify the columns.