3

I am working with Entity Framework Code First, and am trying to create a class that will map to a View. I know how to do it for a table, like below:

[Table("FIL002")]
public class FIL002
{  
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.None)]
    public Int64 Payer_Number { get; set; }
    public string Payer_Name { get; set; }
}

However, I could not find an attribute for View (Like [Table(...)]. Is there one?

raminsh
  • 31
  • 3

2 Answers2

0

Views are queried in the exact same way as tables. Therefore, just use [Table()] as usual.

This does not make the associated DB collection read-only though, so you have to make sure not to try to save any of the objects you get out of it (unless your view is writable of course).

Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
  • How does EF however know it is a view? I do not want the code to allow changes to an instance of this object (will SaveChanges be available ?) – raminsh May 14 '15 at 14:03
  • You have to create the view first. Or you can ignore the SQL view and use LINQ – Peter Smith May 14 '15 at 14:04
  • I don't think EF supports read-only collections in the first place. If you want to make absolutely sure no writes will go through even if somebody tries to do so, you could override `SaveChanges` and manually check if any entities which are supposed to be read only have been changed. – Matti Virkkunen May 14 '15 at 14:08
  • @raminsh - If you make the view read-only, by removing insert/update/delete permissions from the view object, then EF can't update it.. exceptions will get thrown if someone tries. – Erik Funkenbusch May 15 '15 at 06:03
0

There is no direct approach as explained in code-first but you can you DbContext to send raw SQL 'create view' command like this :

public class MyInitializer : CreateDatabaseIfNotExists<MyContext>
{
  protected override void Seed(MyContext context)
  {
    query = "CREATE VIEW [ schema_name . ] view_name [ (column [ ,...n ] ) ] 
            [ WITH <view_attribute> [ ,...n ] ] 
            AS select_statement 
             [ WITH CHECK OPTION ] 
             [ ; ]

            <view_attribute> ::= 
            {
                [ ENCRYPTION ]
                [ SCHEMABINDING ]
                [ VIEW_METADATA ]     
            } ";

    context.Database.SqlCommand(query);
  }
}
Community
  • 1
  • 1
Ognyan Dimitrov
  • 6,026
  • 1
  • 48
  • 70