简体   繁体   中英

Is there a way to get a List of all stored procedure names in C# using Entity Framework?

I know that I can run from an opened database connection:

SELECT * FROM SYS.PROCEDURES

Is there a way to do the equivalent with EF 6.1?

You can run raw sql statements directly from the Database Context object.

SomeDatabaseEntities db = new ...();

var items = db.Database.SqlQuery<Something>("SELECT * FROM SYS.PROCEDURES")

You will need to make a class called Something that will map the results. Should be as easy as having the property names match up.

From the documentation of the method:

The type can be any type that has properties that match the names of the columns returned from the query, or can be a simple primitive type.

Looks like you can just manually map that table using code-first and treat it like any other entity:

[Table("procedures", Schema = "sys")]
public class Procedure
{
    [Column(Order = 0)]
    public string name { get; set; }

    [Key]
    [Column(Order = 1)]
    public int object_id { get; set; }
}

public partial class Model1 : DbContext
{
    public Model1()
        : base("name=Model1")
    {
    }

    public virtual DbSet<Procedure> Procedures { get; set; }
}


using (var context = new Model1())
{
    foreach (var p in context.Procedures)
    {
        Console.WriteLine("{0}: {1}", p.object_id, p.name);
    }
}

Since you're using DB-first, you can wrap a regular view around the system one, then map an entity to it:

create view dbo.procs
as
select * from sys.procedures;

Here you've got a traditional view living in dbo, so EF shouldn't have any trouble with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM