【问题标题】:EF 6 Code First Stored Procedure - Read OnlyEF 6 代码优先存储过程 - 只读
【发布时间】:2014-02-23 15:29:42
【问题描述】:

我已经搜索了一些帖子,但都没有找到。我首先使用 EF6 代码尝试从已在数据库中设置的存储过程中获取结果。我的应用程序很简单,它从两个不同的服务器获取数据,执行一些业务逻辑,然后向用户展示。我可以很好地使用.edmx 文件,它将函数映射到xml 文件中。当我使用 Power Tools 向自己展示 XML 文件时,我没有从下面的代码中看到函数导入,因此我要么缺少设置,要么无法使用 ExecuteFunction()

  1. 我可以先使用ExecuteFunction() 和代码吗?我的存储过程只返回记录。我有这个设置的原因是因为存储过程提供给另一个应用程序,我们希望将查询的所有更改保存在一个地方 (SSMS)。我意识到我可以使用ExecuteStoredQuery / ExecureStoredCommand,但如果我要使用.edmx 模型,我想遵守约定。

  2. 如果我可以使用ExecuteFunction,我应该在哪里以及如何配置我的DbContext 以识别存储过程?通过下面的设置,我收到错误

在容器 {1} 中找不到 FunctionImport {0}

我可以使用 Fluent API 吗?谢谢。

    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);
        }
    }

【问题讨论】:

    标签: c# entity-framework stored-procedures ef-code-first


    【解决方案1】:

    因为它是一个只读存储过程,所以我最终这样做了,而不是试图模仿生成的模型。

     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();
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-01
      • 2014-12-20
      • 1970-01-01
      相关资源
      最近更新 更多