简体   繁体   中英

Entity Framework Include without Relations

I am working on a huge project using Entity Framework. Because I made almost all entities time-dependent it is not possible to use relations between entities anymore (I manage the relations myself). The problem that came up is that I am not longer able to query data as easily as I could before. Say I have an entity called Student . This entity contains a collection of Books (List) which belong to the student. Each book contains an author property which comes from the database as well. To load all the students with theirs book and the corresponding authors I either have to write hundreds of custom queries (fe linq) or I lazy load them which results in a big performance impact. Actually it would be great if I could use the Inlude of Entity Framework without relations. Does anybody know how to achieve this? Thank you.

If Entity Framework is not managing the relations between the tables, then it has no way of using .Include() which would create joins in the SQL call. Your best option would be to add the related entities to the parent as normal, but use the [NotMapped] Attribute. Then you can use a custom SQL call to perform your lookups and populate the properties when you need them. I am confused, however, by your statement that because the entities are "time-dependent" that you can't use relationships, which are simply Foreign Keys in the database... Perhaps there's something else you can do to optimize your entities. If you are managing your own relationships between items, you are offloading a lot of the responsibility from your DB into your app, which seems like a lot of work already.

Update

Implementing an Audit Trail is a fairly standard process in Entity Framework, and probably much easier than managing your relationships. An audit trail basically involves having an event handler for the Context_SavingChanges() method, and then working with your new data and old data through the ObjectStateManager . Adding logic within this loop you could also invalidate or reject additions/updates that don't fall within a specific time frame.

A good example of an Audit Manager is on CodeProject , where the author demonstrates a method to not only store audit information, but also roll back.

如果实体之间没有主键和外键关系,则不能使用Include方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM