19

How can you map an entity to a database view with EF 4 code first?

Is there a way to do this by deriving from the EntityConfiguration classes?

Adam Gordon Bell
  • 3,083
  • 2
  • 26
  • 53

1 Answers1

22

Yes! I found the answer:

You can certainly use Code First to map to a view, just tell Code First that it's a table and it will use the same SQL against the view that it would for a table. Obviously if your view isn't writeable then saving is going to fail if you try and update values in the entities that are based on the view, but we will just delegate to the database so if you don't update these entities then you won't have any issues.

http://social.msdn.microsoft.com/Forums/en-US/adonetefx/thread/f154595c-717e-4703-a81d-ee63633a481e

Adam Gordon Bell
  • 3,083
  • 2
  • 26
  • 53
  • 4
    Nice I didn't know about that but still it is a hack not a feature. – Ladislav Mrnka Aug 30 '10 at 18:01
  • 1
    Is it really a hack? How do you distinguish between a view and a table when writing standard TSQL – mat-mcloughlin Dec 09 '11 at 16:20
  • 6
    @mjmcloug There is some hackery here. If we have EF create the DB, how do we tell it not to create the table? I'm resorting to creating a table the dropping it and creating a view when seeding. – ProfK Apr 24 '12 at 11:44
  • Sorry @ProfK I don't use EF to create the database so can't help you on that one. – mat-mcloughlin May 09 '12 at 11:47
  • 3
    Presumably, if you're trying to map a model to a view, you're talking about an existing database. Although "code first" may be a confusing name when talking about existing database, you can use it with an existing database. – Chris Pratt Dec 06 '12 at 17:20
  • 10
    I like calling Code First with an Existing Database "Code Second" – Christopher Stevenson Sep 23 '13 at 16:55
  • 1
    "you're talking about an existing database" What about a view created to work around a EF6 incapability with multiple projections and union? – Davi Fiamenghi Feb 25 '15 at 20:04