I am trying to create a custom Entity Framework (4.2) entity that would be mapped to my database like it would be done in a Code first approach.
The issue is that my entity framework data model is using Database first.
How can I add my custom entity to entity framework’s context?
If by the Database first you mean that you already have EDMX created from exiting database you simply cannot use code first. You must create table and update model (EDMX) from the database to include it in EDMX.
Edit based on comment:
Well this is possible. You can either create BriefUser as common class and use projection in query.
You can even refactor former code to reusable extension method:
and use it like:
It is also possible to define your new class as “entity view”. The first problem is that each table can be mapped to only one entity (except some advanced concepts like inheritance or splitting) so you cannot define your BriefUser as a new entity type because mapping both
UserandBriefUsertoUserTblwould violate this rule. You must use special construct called QueryView.QueryViewis view in mapping level. It allows you to create new mapped type which is projection of existing mapped entities defined directly in EDMX’s MSL part. The projection is defined as custom Entity SQL query. The problem is thatQueryViewhas limitations:QueryViewand you must write Entity SQL query yourselves.This is not possible. Your
BreifUseris only projection / view and EF is not able to track changes back to originating tables so you cannot addBreifUserto context and persist it. In case ofQueryViewyou can achieve it if you define custom stored procedures which will no how to decomposeBreifUserand modify all related tables. These stored procedures must be imported to the EDMX and mapped to data modification operations of the view entity. Btw. same will happen if you map your entity to the database view because EF takes all views as read-only.