0

I was trying to create a view from EF code-first. Unfortunately after my research, I couldn't find any topics about it.

I can get my SQL view queries using EF database-first, but can't get it from code-first.

Can someone help me ?

Thanks...

enter image description here

1 Answer 1

1

You can create views inside a Migration using the Sql method:

public partial class Migration : DbMigration
{
    public override void Up()
    {
        this.Sql("CREATE VIEW dbo.MyView AS (etc)");
    }

    public override void Down()
    {
        this.Sql("DROP VIEW dbo.MyView");
    }
}

There's not any problem to map an entity to a view, in your dbContext:

public class MyDbContext : DbContext
{
    public DbQuery<MyModelView> MyView
    {
        get
        {
            // Don't track changes to query results
            return Set<MyModelView>().AsNoTracking();
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

EF says: The entity type is not part of the model for the current context.
@hakan maybe you are trying to modify the state of the entity and you can not do that..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.