I work with EF Core 3.1 and I want load related data of child tables via explicit loading.
I have 4 tables - A, Aa, Ab, A_Ab (1 principal and 2 related tables - 1:N and M:N (scheme on picture))
enter image description here
If I wanted to use Eager Loading code syntax is here:
var result = context.A
.Include(x => x.Aa)
.Include(x => x.A_Ab)
.ThenInclude(x => x.Ab)
.ToList();
But I want load only A and then with Explicit Loading Aa, Ab - any idea how to do that?
Related
I am trying to create a query with ASP.NET Core EF Core and Linq that would give me a List of users based on two different lists, something like this:
return await _context.Users
.Include(u => u.PropertyOwners)
.ThenInclude(po => po.Property)
.ThenInclude(p => p.PropertyTenantLeases)
.Include(u => u.PropertyOwners)
.ThenInclude(po => po.Owner)
.Where(u => u.Id == userID)
.Select(u => new List<User>()
{
u.PropertyTenantLeases.Select(ptl => ptl.Tenant).ToList()
u.PropertyOwners.Select(po => po.Owner).ToList()
}).FirstOrDefaultAsync();
The tables that are used in this query are connected in the following way:
Everything is fine with this query except for the Select, with the Select I am trying to achieve that it returns a list of all the tenants in the PropertyTenantLeases table which is a junction table togheter with all the Owners form the PropertyOwners junction table (both Tenant and Owner are IdentityUser classes. When I right this query like this I get the following error:
The best overloeaded Add method 'List<User>.Add(User)' for the collection initializer has some invalid arguments
and also
Argument 1: cannot convert from 'System.Collections.Generic.List<RosyMasterDBManagement.Models.User>' to 'RosyMasterDBManagement.Models.User'
Joining two list is called a union in Linq -- I believe that is what you want:
note: I still can't test this since you gave a picture of the data model instead of the code that would allow me to be certain of how to implement. expect the fields to be named incorrectly etc.
var ownerlist = _context.Users
.Include(u => u.PropertyOwners)
.ThenInclude(po => po.Owner)
.ToList();
var tenantlist = _context.Users
.Include(u => u.PropertyOwners)
.ThenInclude(po => po.Property)
.ThenInclude(p => p.PropertyTenantLeases)
.ThenInclude(po => po.Tenant)
.ToList();
return ownerlist.Union(tenantlist);
I don't believe you need await() since ToList() forces it to not be lazy. But I could be wrong about that.
My entity "TimeRecord" has a collection of "WayPoints" and two one-to-one properties "Location" and "WayData".
Each property can be null.
I need to export all Time Records with initialized properties for a specific User.
I actually had a working solution but then I started to use NHibernateProiler and first I noticed that this code results in a ridiculous number of query’s against db.
var query = (from timeRecord in Session.Query<TimeRecord>()
.Where(tr => tr.User.Id == userid)
select timeRecord);
Then I changed my code to:
var query = (from post in Session.Query<TimeRecord>()
.Fetch(x => x.Location)
.Fetch(x => x.WayData)
.FetchMany(x => x.WayPoints)
.Where(tr => tr.User.Id == userid)
select post);
Which lead me to the Cartesian product problem.
Right now I’m experimenting with this piece of code:
var sql1 = "from TimeRecord b left outer join fetch b.Location where b.User.Id=:User_id";
var sql2 = "from TimeRecord b left outer join fetch b.WayData where b.User.Id=:User_id";
var sql3 = "from TimeRecord b left inner join fetch b.WayPoints where b.User.Id=:User_id";
var result = Session.CreateMultiQuery()
.Add(Session.CreateQuery(sql1))
.Add(Session.CreateQuery(sql2))
.Add(Session.CreateQuery(sql3))
.SetParameter("User_id", userid)
.List();
But I can’t say if this is the correct approach or if this is even possible with nHibernate. Can someone help me with that?
The 1+N issue is a usual with the entity/collection mapping and ORM tools. But NHibernate has a very nice solution how to manage it properly. It is called:
19.1.5. Using batch fetching
This setting will allow:
To continue querying the root entity (TimeRecord in our case)
No fetching inside of the query (Session.Query<TimeRecord>()). That means we do have support for correct paging. (Take(), Skip() will be executed over the flat root table)
All the collections will be loaded with their own SELECT statements (could seem as disadvantage but se below)
There will be much more less SELECTs then 1+N. All of them will be batched. E.g. by 25 records
all the native mapping (lazy loading of collections) will still be in place...
The xml mapping example:
-- class level
<class name="Location" batch-size="25 ...
-- collection level
<batch name="Locations" batch-size="25" ...
I would suggest to apply that over all your collections/classes. With Fluent mapping it could be done also with conventions
The fluent mapping:
// class
public LocationMap()
{
Id(x => x....
...
BatchSize(25);
// collection
HasMany(x => x.Locations)
...
.BatchSize(25);
I want to hydrate a collection of entities by passing in a List of Ids and also preserve the order.
Another SO answer https://stackoverflow.com/a/15187081/1059911 suggested this approach to hydrating the entities which works great
var entities = db.MyEntities.Where(e => myListOfIds.Contains(e.ID)).ToList();
however the order of entities in the collection is different from the order of Ids
Is there a way to preserve the order?
May be that helps:
var entities = db.MyEntities
.Where(e => myListOfIds.Contains(e.ID))
.OrderBy(e => myListOfIds.IndexOf(e.ID)).ToList();
EDIT
JohnnyHK clarified that this will not work with LINQ to Entities. For this to work you need to order IEnumerable instead of IQueryable, since IQueryProvider don't know how to deal with local list IndexOf method when it sends query to server. But after AsEnumerable() OrderBy method deals with local data. So you can do this:
var entities = db.MyEntities
.Where(e => myListOfIds.Contains(e.ID))
.AsEnumerable()
.OrderBy(e => myListOfIds.IndexOf(e.ID)).ToList();
Entity Framework contains a subset of all of the LINQ commands so you won't have all the commands that LINQ to Objects has.
The following approach should give you your list of MyEntities in the same order as supplied by myListOfIds:
var entities = myListOfIds.Join(db.MyEntities, m => m, e => e.ID, (m,e) => e)
.ToList();
I'm having problems with this query using entity framework 4:
List<SomeResult> test = (from a in _entities.TableA
select new SomeResult
{
TestB = a.TableB.Name,
TestCDict = a.TableC.ToDictionary(x => x.SomeKey, x => x.SomeValue)
}).ToList();
It gives this error:
"Cannot compare elements of type 'System.Data.Objects.DataClasses.EntityCollection`1'. Only primitive types (such as Int32, String, and Guid) and entity types are supported."
How can I redo this query so it'll work? from a in _entities.TableA from c in a.TableC ....ToDictionary(.. ?
/Lasse
The problem is, that you are doing query against database. And LINQ provider that you are using, actually don't execute any of the operations, that you have written. It only tryes to translate all your code in Select into database query. Obviously, it can't parse really complex statents, like you have written with ToDictionary().
You can simply load all data from entities into memory, and then do all your dictionary stuff. Then your code will actually be executed, and should work.
Like:
List<SomeResult> test = from a in (from aa in _entities.TableA).AsEnumerable())
select new SomeResult
{
TestB = a.TableB.Name,
TestCDict = a.TableC.ToDictionary(x => x.SomeKey, x => x.SomeValue)
}).ToList();
Of course you can use DB side filtering in the inner query (before AsEnumerable()) to narrow amount of data loaded into memory.
I have a piece of code that I don't know how to improve it.
I have two entities: EntityP and EntityC.
EntityP is the parent of EntityC. It is 1 to many relationship.
EntityP has a property depending on a property of all its attached EntityC.
I need to load a list of EntityP with the property set correctly. So I wrote a piece of code to get the EntityP List first.It's called entityP_List. Then as I wrote below, I loop through the entityP_List and for each of them, I query the database with a "any" function which will eventually be translated to "NOT EXIST" sql query. The reason I use this is that I don't want to load all the attached entityC from database to memory, because I only need the aggregation value of their property. But the problem here is, the looping will query the databae many times, for each EntityP!
So I am wondering if anybody can help me improve the code to query the database only once to get all the EntityP.IsAll_C_Complete set, without load EntityC to memory.
foreach(EntityP p in entityP_List)
{
isAnyNotComoplete = entities.entityC.Any(c => c.IsComplete==false && c.parent.ID == p.ID);
p.IsAll_C_Complete = !isAnyNotComoplete;
}
Thank you very much!
In EF 4, you can do:
var ids = entityP_List.Select(p => p.ID);
var q = (from p in entities.entityP
where ids.Contains(p => p.ID)
select new
{
ID = p.ID,
IsAll_C_Complete = !p.entityCs.Any(c => !c.IsComplete)
}).ToList();
foreach (var p in entityP_List)
{
p.IsAll_C_Complete = q.Where(e.ID == p.Id).Single().IsAll_C_Complete;
}
...which will do the whole thing in one DB query. For EF 1, Google BuildContainsExpression for a replacement for the .Contains( part of the above.
I would base EntityP on a SQL View instead of a table. Then I would define the relationship, and aggregate the value for child table within the view.