Entity Framework (v6) Eager-Loading weird behaviour - 'Gotcha' - entity-framework-6

Should the following two queries be equivalent?
(note the placement of .Include)
== (V1)
using (var ctx = new Entities()) {
ctx.Configuration.ProxyCreationEnabled = false; //return stronglyTyped Entity, not dynamic entity...
IQueryable<TB_MyHeader> query = from hd in ctx.TB_MyHeader.Include(h => h.TB_MyLines)
join wo in ctx.TB_AnotherTable on hd.fkId equals wo.ID
where wo.woPk == #id
orderby hd.PoItem
select hd;
var headerPlusLines = query
.AsNoTracking()
.ToList();
return headerPlusLines;
}
== (V2)
using (var ctx = new Entities()) {
ctx.Configuration.ProxyCreationEnabled = false; //return stronglyTyped Entity, not dynamic entity...
IQueryable<TB_MyHeader> query = (from hd in ctx.TB_MyHeader
join wo in ctx.TB_AnotherTable on hd.fkId equals wo.ID
where wo.woPk == #id
orderby hd.PoItem
select hd)
.Include(h => h.TB_MyLines);
var headerPlusLines = query
.AsNoTracking()
.ToList();
return headerPlusLines;
}
The first version (V1) may not fetch children into the Nav property, depending on combinations of how ProxyCreationEnabled, LazyLoadingEnabled are set true/false.
In fact, the opposite of expected result occurs; if i set LazyLoadingEnabled = false, no children load at all;
When i would have expect it to 'dont be lazy, load it now !'
Whats going on?

Related

How to include FirstOrDefault() in ToList()

I want to get only one file for each recipe.
var UploadedFiles = (from rec in db.Recipes
join files in db.Files on rec.Id equals files.RecipeId
select new
{
files.Id,
files.Path,
files.RecipeId,
rec.Name,
rec.Description,
rec.Category,
rec.CookTime
}).ToList();
return new JsonResult { Data = UploadedFiles, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
You could use group join instead of regular join, I presume it is also more efficient than the previous answer (with the let), although I am not fully aware of EF query optimizations in this case
var UploadedFiles = (from rec in db.Recipes
join files in db.Files on rec.Id equals files.RecipeId into g
let firstFile = g.FirstOrDefault()
select new
{
firstFile.Id,
firstFile.Path,
firstFile.RecipeId,
rec.Name,
rec.Description,
rec.Category,
rec.CookTime
}).ToList();
Update
since I don't use EF, I can't really confirm whether or not it handles nulls but I have been informed it doesn't you would have to remove nulls.
var UploadedFiles = (from rec in db.Recipes
join files in db.Files on rec.Id equals files.RecipeId into g
let firstFile = g.FirstOrDefault()
where firstFile != null
select new
{
firstFile.Id,
firstFile.Path,
firstFile.RecipeId,
rec.Name,
rec.Description,
rec.Category,
rec.CookTime
}).ToList();
You can try the following...
var UploadedFiles = (from rec in db.Recipes
from files in db.Files.FirstOrDefault(f => f.RecipeId == rec.Id)
select new
{
files.Id,
files.Path,
files.RecipeId,
rec.Name,
rec.Description,
rec.Category,
rec.CookTime
}).ToList();
return new JsonResult { Data = UploadedFiles, JsonRequestBehavior =
JsonRequestBehavior.AllowGet };

How do I remove the foreach from this linq code?

I'm fairly new at MVC and linq and viewmodels in particular. I managed to get a create and index views to work. The "insert" wasn't as hard as the "list".
I have this linq query:
public ActionResult Index()
{
List<BlendElVM> BEVM = new List<BlendElVM>();
var list = (from Blend in db.blends
join BlendEl in db.blendEl on Blend.ID equals BlendEl.ID
select new
{
Blend.ID, Blend.Title, Blend.TransDt, BlendEl.Comment
}).ToList();
foreach (var item in list)
{
BlendElVM o = new BlendElVM(); // ViewModel
o.Comment = item.Comment;
o.Title = item.Title;
o.TransDt = item.TransDt;
o.ID = item.ID;
BEVM.Add(o);
}
return View(BEVM);
}
What I'm not sure about is the "foreach" section. When I'm running in debug, the "list" shows up fine, but if I comment out the "foreach" I get an error - ie not expecting the model. What does the foreach do? It has to do with the database, but I don't understand the where it is using the "o" and setting the columns. I thought it would all be in one linq query. Is it possible to combine the two and eliminate the "foreach"?
var BEVM = (from blend in db.blends
join BlendEl in db.blendEl on Blend.ID equals BlendEl.ID
select new BlendELVM
{
ID = blend.ID,
Title = blend.Title,
TransDT = blend.TransDt,
comment = blendEl.Comment
}).ToList();
I believe that the foreach is needed in order to read every element in the object so in this case you have:
BlendElVM o = new BlendElVM();
So you're creating and object named " o " of the type BlendELVM and this object contains all the attributes that you declared before which are: ID, Title, TransDT, etc
When you put:
foreach (var item in list)
{
BlendElVM o = new BlendElVM(); // ViewModel
o.Comment = item.Comment;
o.Title = item.Title;
o.TransDt = item.TransDt;
o.ID = item.ID;
BEVM.Add(o);
}
You're assigning to the new object o the item that you're reading in the list and in the end adding it to the BVEM list and answering if you can combine them i will say no because at first you're declaring the query and then you're reading the items on the list and assining them to the BEVM list

Entity Framework - How can I check whether an object is under another object's Hierarchy?

I have an table called Contents. There's one to many relationship on Contents, so each content can have a parent and children. I'm using EF Code First, so I have an entity Content which has Id, ParentId, Parent and Children properties.
Now, I'm building an ajax based tree of Contents. I have a simple action that returns a JSON of one level of Contents, based on parentId:
public JsonResult GetContents(int? parentId = null)
{
return Json(db.Contents
.Where(p => p.ParentId == parentId)
.Select(p => new
{
id = p.Id,
name = p.Name
});
}
The next thing I want to do is to automatically select some value. The problem is that the value can be deep inside the hierarchy of the tree, so for each content I'll need to know whether or not the selected value is a child or grandchild and so forth, of it.
public JsonResult GetContents(int? parentId = null, int selectedValue)
{
return Json(db.Contents
.Where(p => p.ParentId == parentId)
.Select(p => new
{
id = p.Id,
name = p.Name
isSelectedValueUnderThisHierarchy: // How can I efficiently implement this?
});
}
It's easy to implement with a lot of queries, but I'm trying to make things as efficient as possible, and EF doesn't provide any Recursive methods as far as I know, so I really have no clue where to start.
You could first build a list of all the ParentIds from the selected value. Depending on the size of your Contents table, you could first load the data, then loop through without making extra queries to the database.
db.Contents.Load();
var selectedItem = db.Contents.Find(selectedValue);
var parents = new List<int>();
while (selectedItem.ParentId != null)
{
parents.Add(selectedItem.ParentId.Value);
selectedItem = selectedItem.Parent;
}
Alternatively, you could use CTE (Common Table Expression).
var parents = db.Database.SqlQuery<int>("sql statement");
Once you have a list of parents, you can use Contains.
return Json(db.Contents
.Where(p => p.ParentId == parentId)
.Select(p => new
{
id = p.Id,
name = p.Name
isSelectedValueUnderThisHierarchy = p.ParentId.HasValue && parents.Contains(p.ParentId.Value)
});
UPDATE: CTE Example
You'd probably want to use a stored procedure, but this code should work.
var sql = #"with CTE as
(
select ParentId
from Contents
where Id = {0}
union all
select Contents.ParentId
from Contents
inner join CTE on Contents.Id = CTE.ParentId
)
select *
from CTE
where ParentId is not null";
var parents = db.Database.SqlQuery<int>(string.Format(sql, selectedItem)).ToList();

load navigation properties with filter for Entity Framework 4.3

Few days back I put a question regarding mapping two classes Message and MessageStatusHistory using EF. The mapping is going fine but I am facing some problems with the navigation property StatusHistory in class Message that relates it to MessageStatusHistory objects. I am loading the messages for one user only and want to the statuses pertaining to that user only. Like I would want to show if the user has marked message as read/not-read and when. If I use default loading mechanism like following it loads all the history related to the message irrespective of the user:
IDbSet<Message> dbs = _repo.DbSet;
dbs.Include("StatusHistory").Where(x=>x.MessageIdentifier == msgIdentifier);
To filter history for one user only I tried following trick:
IDbSet<Message> dbs = _repo.DbSet;
var q = from m in dbs.Include("StatusHistory")
where m.MessageIdentifier == msgIdentifier
select new Message
{
MessageIdentifier = m.MessageIdentifier,
/*OTHER PROPERTIES*/
StatusHistory = m.StatusHistory
.Where(x => x.UserId == userId).ToList()
};
return q.ToList();//THROWING ERROR ON THIS LINE
I am getting the error:
The entity or complex type 'MyLib.Biz.Message' cannot be constructed in a LINQ
to Entities query.
I have tried by commenting StatusHistory = m.StatusHistory.Where(x => x.UserId == userId).ToList() also but it has not helped.
Please help me in getting Messages with filtered StatusHistory.
EDIT:- above is resolved with this code:
var q = from m in _repository.DBSet.Include("Histories")
where m.MessageIdentifier == id
select new {
m.Id,/*OTHER PROPERTIES*/
Histories = m.Histories.Where(x =>
x.SenderId == userId).ToList()
};
var lst = q.ToList();
return lst.Select(m => new Message{
Id = m.Id, MessageIdentifier = m.MessageIdentifier,
MessageText = m.MessageText, Replies = m.Replies,
ReplyTo = m.ReplyTo, Histories = m.Histories, SenderId =
m.SenderId, SenderName = m.SenderName, CreatedOn = m.CreatedOn
}).ToList();
But if I try to include replies to the message with:
from m in _repository.DBSet.Include("Replies").Include("Histories")
I am getting error on converting query to List with q.ToList() for Histories = m.Histories.Where(x=> x.SenderId == userId).ToList().
About your EDIT part: You cannot use ToList() in a projection, just leave it an IEnumerable<T> and convert to a List<T> when you construct the Message. You also don't need to create two list objects, you can switch from the LINQ to Entities query to LINQ to Objects (the second Select) by using AsEnumerable():
var list = (from m in _repository.DBSet
where m.MessageIdentifier == id
select new {
// ...
Histories = m.Histories.Where(x => x.SenderId == userId)
})
.AsEnumerable() // database query is executed here
.Select(m => new Message {
// ...
Histories = m.Histories.ToList(),
// ...
}).ToList();
return list;
Be aware that Include has no effect when you use a projection with select. You need to make the properties that you want to include part of the projection - as you already did with select new { Histories.....

adding a record to a LINQ object (concat) taking values from another

Hi i'm looking for some help in how to append rows to an existing LINQ object. In the controller method below I have two result sets, i'm looping the Sites and want to add a record to the 'results' object for each record in the Sites object.
I've tried concat etc but not getting anywhere, just need s small example to assist, many thanks in advance, J
public IQueryable<UsersToSite> FindAllUsersToSites(int userId,SystemType obj)
{
var results = (from usersToSite in this._db.UsersToSites
where usersToSite.UserId == userId &&
usersToSite.SystemTypeId == obj
orderby usersToSite.Site.SiteDescription
select usersToSite);
// Now for each remaining Site append a record thats not physically in the database. From the view the user will be able to click these records to ADD new
// I'll then build in a search
var sites = (from site in this._db.Sites
where !(from o in _db.UsersToSites where (o.UserId == userId && o.SystemTypeId == obj) select o.SiteId).Contains(site.SiteId)
orderby site.SiteDescription
select site);
foreach (var site in sites)
{
// HERE I want to create the new ROW in results object
//results = new[results] { new { UsersToSiteId = null, AccessTypeId = null } }.Concat(sites);
//SiteId=site.SiteId,
//UsersToSiteId = 0,
//AccessTypeId = 0,
//UserId = userId
}
return results;
}
I don't think you can, if you want to have keep queryable.
However, if you materialize the results with ToList(), then you can:
var sites = (from site in this._db.Sites
where !(from o in _db.UsersToSites where (o.UserId == userId && o.SystemTypeId == obj) select o.SiteId).Contains(site.SiteId)
orderby site.SiteDescription
select site)
.ToList();
sites.Add(new Site { UsersToSiteId = null, etc });
If it was LINQ to Objects, you could do Concat.
The problem here that it can't do ConcatLINQ query that will have one part from SQL and another from objects. You need to materialize results first and then concat to object.

Resources