That simple. I need to create a View using Code First. I found nothing about this on google nor SO. Is there a way to accomplish this?
I need that view to be created and queried using linq, so it's not a solution to create it using an script on Database creation, for example:
var results = from c in db.Customer
join v in db.MyView on c.Id equals v.Id
select c;
A work around is also acceptable. I need a way to query entities against non-constant/ non-entities values.
You cannot create views with EF Code First approach. If you want to create view then execute creation sql script in Seed
method. But you'll still not be able to map entity to this view, except hacking model by creating and droping table with same name as your view will have.
Some helpful links:
you must manually create the view, just like AnatoliiG stated. (Adding index to a table).
You add the name of the view as an attribute to your class
[Table("UserDTO")]
public class UserDTO
{
/* Class code here */
}
You can create an empty migration by specifying the -IgnoreChanges attribute at the end
Add-Migration MigrationName -IgnoreChanges
This gives you an empty migration script that you can manually modify.
You can use your db context to execute your code in your migration script
public partial class editUserDTO : DbMigration
{
public override void Up()
{
string script =
@"
CREATE VIEW dbo.UserDTO
AS SELECT p.PersonId AS UserId, p.FirstName, p.LastName, u.UserName
FROM dbo.Users u
INNER JOIN dbo.People p ON u.PersonId = p.PersonId";
BloggingContext ctx = new BloggingContext();
ctx.Database.ExecuteSqlCommand(script);
}
public override void Down()
{
BloggingContext ctx = new BloggingContext();
ctx.Database.ExecuteSqlCommand("DROP VIEW dbo.UserDTO");
}
}