0

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?

Robert
  • 4,306
  • 11
  • 45
  • 95

3 Answers3

3

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.

gunr2171
  • 16,104
  • 25
  • 61
  • 88
3

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);
    }
}
Joe Enos
  • 39,478
  • 11
  • 80
  • 136
1

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.

Joe Enos
  • 39,478
  • 11
  • 80
  • 136
  • EF will have issues with the primary key, since it can't figure out which column should be the key - that probably won't matter in your case, but take a look at [this question](http://stackoverflow.com/questions/1013333/entity-framework-and-sql-server-view) for some discussion on that - you may be able to tweak the query a little to make the designer a little smarter. – Joe Enos Jul 28 '14 at 15:55