问题
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