Is there an attribute like [Table()] to create a class that maps to a view in EF Code First?

倖福魔咒の 提交于 2019-12-10 17:52:37

问题


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?


回答1:


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).




回答2:


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);
  }
}


来源:https://stackoverflow.com/questions/30239314/is-there-an-attribute-like-table-to-create-a-class-that-maps-to-a-view-in-ef

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!