1

Is it possible to add fields to an entity framework class that rather than being mapped to a column in a table instead map to a SQL query?

For a contrived example (NB: This is not what I'm actually trying to do just an easier to explain example of what I'm trying to accomplish) I want my class to have a TableCount field that holds the result of SELECT COUNT(*) FROM MyTable at the time the object was loaded from the db.

EDIT: I should have mentioned this in my original post but I'm using POCO classes.

1 Answer 1

1

You cannot do it directly with entity mapped to a database but there are two ways how to achieve it with a new entity type containing columns from your original entity and your additional computed columns:

  • Create database view and map that view - this is fully automatic way maintained by EDMX designer for you
  • Write query to populate whole new entity type and map it manually in DefiningQuery. The disadvantage is that it requires manual EDMX editing and without additional (commercial) tool also manual maintenance of EDMX because standard VS EDMX Designer overwrites edited SSDL part every time you select update from database.
Sign up to request clarification or add additional context in comments.

2 Comments

Please see my edit. I'm using POCO classes so the EDMX designer doesn't really enter into it.
POCO classes are still possible with EDMX. If you are using code first you cannot map custom queries to your classes but You can use the first approach if you are using code mapping with existing database.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.