Nested relationships never end entity framework - c#

I have 3 tables: Courses, Departments, and Universities.
When I pull the information from the database (using entity framework), I am attempting to map, for example, a Course to a CourseDTO. I am trying to set it up in such a way that the CourseDTO automatically checks if the relationships exist (is not null), then hook up the relationship in the DTO.
Problem is once I run:
db.Courses.Include(c=>c.Department).Include(c=>c.University)
It maps every nested permutation of these relationships, so my automatic mapping to the DTO just creates a stackoverflow because it goes on forever. (eg. Course maps the Department which maps the Courses in that Department, which maps the Department, etc.)
What is the best solution to avoid this problem?

I would suggest turning off Lazy Loading for EntityFramework via
context.Configuration.LazyLoadingEnabled = false
This will prevent the sub-objects that you did not explicitly include from being expanded by Entity Framework when they are accessed.
Either that or create a custom mapping method to include only the objects you want in your DTO.

Related

Adding a property to an association

Having two tables Courses and Employees, i have a many to many relationship between the two. EF automatically generates an intermediary table called CoursesEmployees.
I want to add a property IsPassed to that intermediary.
I could do this in MySQL but i won't know where to map it to in my data model. Is it possible? Preferably in the data model because i work model-first.
I use all of the latest versions.
The way to achieve what you want in a Model First approach is to explicitly model the relation table and add your IsPassedproperty to it, as I've done below. There is a 1-to-m relationship between Course and Course_Employee entities as well as a 1-to-n relationship between Employee and Course_Employee entities. The combination of the two one-to-many relationships creates the many-to-many relationship between Course and Employee entities.

Is it possible to have an entity that descends from two different entities

In the database, I have two tables PersonalDetails and Officers. There's one-to-many relationship between them.(One person can hold different positions in the same company at different periods). I'm using Entity Framework code first approach to communicate with the database. So far I had one entity called Officer that mapped to a join of the above two tables, But now that I have to perform CRUD operations on Officer this makes me have separate entities for them. Now the question is can I somehow leave the Officer entity as it is but instead of mapping to a view in the database have it descend from the two entities I will create and possibly be able insert/update it and have the changes reflected on the corresponding entities.
Here are the entities:(I've omitted the C# rules for a class definition for brevity )
PersonDetails{Pin,FirstName,LastName}
Officer{OfficerID,Pin,Position,ValidThru}
I will use these entities when I need to update/insert. But in user administration panel, I need to show combined information about users(or Officers).For instance:
Pin FirstName LastName Position ValidThru

Prevent the loading of subclass table rows in TPT inheritance on Entity Framework

I have the following table hierarchy in my database which i map to an Entity Framework model (Database First) using the Table-Per-Type (TPT) inheritance pattern:
The mapping in the EF model is straightforward: AssetContent is a base abstract class while the other 2 are concrete subclasses.
The AssetContent table participates into a many-to-many relationship with another table which, to keep the picture clear, is omitted.
My question is, how do i build a Linq-to-Entities query to load the related AssetContent table using Include() such that the 2 'sub-tables' are not loaded at all? This is especially important for the DatabaseAssetContent table, whose BinaryContent field may be quite large and of no relevance to the issuer of the query i want to build. As far as i observed, Entity Framework automatically loads the entire hierarchy for a table, whether lazy loading is enabled or not, but i am interested in loading only the rows in the AssetContent table.
Is such a query possible using Linq-to-Entities (for Entity Framework 6)?
Eventually, i moved the AssetContent table's fields (except the Id) into another, new table, called AssetContentWithMetadata, which has a 1-1 relationship to the AssetContent table. This way, the AssetContent table remains indeed a bit awkward, with a single field (the ID), but now i can load the metadata table alone, without burdening it with the contents as well.

Entity framework update change

I have an entity model with a self relation (parent/child). My entity named Article has a property called parent. This parent is in fact the relation, and ParentID which is the field in the relation. In ef 4 i did this:
using (var dbContext= new DataBaseModel())
{
ArticleTable newEntity= new ArticleTable();
newEntity.name="childArt";
newEntity.ParentID = 1;
dbContext.ArticleTable.Add(newEntity);
dbContext.SaveChanges();
//after calling save I can do this
var parentName = newEntity.Parent.Name;
}
With entity framework 6, this doesn't work any more, I have get the entity from the database again in order to get the related parent entity. Is this because of changes to lazyloading? what should i do different.
The difference is that in EF 4 entities were generated with piles of code that took care of change notification and lazy loading. Since then, the DbContext API with POCOs has become the standard.
If you want the same behavior as with the old 'enriched' entities you must make sure that lazy loading can occur by a number of conditions:
The context must allow lazy loading. It does this by default, but you can turn it off.
The navigation properties you want to lazy load must have the virtual modifier, because
EF must create dynamic proxies. These proxies somewhat resemble the old generated entities in that they are able to execute lazy loading, because they override virtual members of the original classes.
The last (and maybe second) point is probably the only thing for you to pay attention to. If you create a new object by new, it's just a POCO object that can't do lazy loading. However, if you'd create a proxy instead, lazy loading would occur. Fortunately, there is an easy way to create a proxy:
ArticleTable newEntity= dbContext.ArticleTables.Create();
DbSet<T>.Create() creates dynamic proxies -
if the underlying context is configured to create proxies and the entity type meets the requirements for creating a proxy.

Why does LoadProperty not load the related entities for 1:N relationships? (CRM2011, early binding entity classes)

Suppose I have a custom entity new_someentity which has 2 other related entities: an "owner" entity which I'll call new_ownerentity (this is a N:1 relationship) and a "child" entity which I'll call new_childentity (1:N relationship).
I'm attempting to populate the related entities by calling LoadProperty:
new_someentity en = context.new_someentitySet.First();
context.LoadProperty(en, "new_someentity_new_ownerentity");
context.LoadProperty(en, "new_someentity_new_childentity");
Afterward, en.new_someentity_new_ownerentity is populated as I expect it to be with a reference to the owner entity, but en.new_someentity_new_childentity is simply still null. No errors are produced.
What's the deal?
On a side note, is there really not a concise way to load a related entity for an IEnumerable of entities without needing to use LoadProperty on each entity individually? This seems like a pretty classic case of an N+1 queries issue.
Just because you think it should return an empty list when the object doesn't have any child entities doesn't mean that's the way LoadProperty works.
So for anyone else who comes upon this:
LoadProperty will leave the property null when there aren't any related records for that record, even on 1:N relationships.

Categories