EF 6 Code First Stored Procedure - Read Only

2019-04-05 17:20发布

I have searched a few posts, but have come up short. I am using EF6 code first trying to get results from a stored procedure that is already setup in a database. My application is simple, it takes data from two different servers, performs some business logic, and then shows the user. I can use the .edmx file fine, which maps the function in the xml file. When I use Power Tools to show myself the XML file I do not see the function import from my code below so I am either missing a setup or I cannot use ExecuteFunction().

  1. Can I use the ExecuteFunction() with code first? My stored procedure only returns records. The reason I have this setup is because the stored procedure feeds another application and we want to keep all the changes to the query in one place (SSMS). I realize I could use ExecuteStoredQuery / ExecureStoredCommand, but I wanted to stick to the convention if I were to use the .edmx model.

  2. If I can use ExecuteFunction, where and how do I configure my DbContext to recognize the stored procedure? With my setup below I receive the error

The FunctionImport {0} could not be found in the container {1}

Can I use Fluent API? Thanks.

    public class JobContext : DbContext
    {
        public JobContext()
            : base("name=JobContext")
        {
            // My context will only define a slice of the database
            Database.SetInitializer<JobContext>(null);
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.ComplexType<Job>();
        }

        public virtual ObjectResult<Job> uspGetJobs(string startDate)
        {
            var startDateParameter = startDate != null ?
                new ObjectParameter("startDate", startDate) :
                new ObjectParameter("startDate", typeof(string));

            return ((IObjectContextAdapter)this).ObjectContext.<Job>("uspGetJobs", startDateParameter);
        }
    }

1条回答
Anthone
2楼-- · 2019-04-05 17:30

since it was a read only stored procedure I ended up doing this instead of trying to mimick the generated model.

 public virtual List<Jobs> uspGetJobs(string startDate)
 {
    var startDateParameter = startDate != null ?
                             new SqlParameter("startDate", startDate) :
                             new SqlParameter("startDate", typeof(string));

    return this.Database.SqlQuery<PlannedJobs>("uspGetPlannedJobs @startDate, @locationCode", startDateParameter, locationCodeParameter).ToList();
 }
查看更多
登录 后发表回答