7

I define my model in Entity Framework (code first), but how can I define a stored procedure in my model? I want to create my model and have it generate the stored procedure in my database when my database is generated from my model.

2
  • i want define a model from my Store procedure.and when i use my model for the first time Entity generate my Store procedure in SQL server. Commented Jan 10, 2012 at 19:51
  • Is this related question of any help? stackoverflow.com/questions/4845246/… Commented Jan 10, 2012 at 19:56

2 Answers 2

14

Description

There is no built in direct mapping support for stored procedures in Entity Framework code first at the moment. But you can exec any sql query (create your stored procedure) like in my sample.

Sample

public class MyDatabaseContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        DbCommand cmd = Database.Connection.CreateCommand();
        cmd.CommandText = "create stored procedure ....";
        cmd.ExecuteNonQuery();
    }   
}

More Information

Sign up to request clarification or add additional context in comments.

2 Comments

you answer is so useful for me.
I got the following error: ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.
2

I'm using Entity Framework 6 so things may have changed. The database is not created in OnModelCreating, but it did work in the DbInitializer like this...

public class MyDbInitializer : DropCreateDatabaseIfModelChanges<MyDbContext> {
    protected override void Seed(MyDbContext context) {
        string sql = @"CREATE PROCEDURE...";
        context.Database.ExecuteSqlCommand(sql);

        base.Seed(context);
    }
}

2 Comments

Will changes to a stored procedure created in this way be tracked by migrations?
@Craig, I would think so. I did not test it.

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.