【问题标题】:Entity Framework Stored Procedures and POCO实体框架存储过程和 POCO
【发布时间】:2012-04-13 09:31:29
【问题描述】:

我需要有关在 Entity Framwork 4.x 中使用存储过程以将数据返回到 POCO 对象的建议。我不想将数据从实体对象复制到 POCO 对象。我想执行一个存储过程并将数据直接加载到我的 POCO 类中。

有没有办法做到这一点?我是否需要像您在 Nhibernate 中使用的某种映射?如果是这样,这个映射可以是基于属性的吗?

编辑:使用下面贾斯汀的帮助,我发现这样做的方法是:

SqlParameter p1 = new SqlParameter("@p1", "xxxx");
SqlParameter p2 = new SqlParameter("@p2", "yyyy");

SqlParameter[] parameters = new SqlParameter[2];
parameters[0] = p1;
parameters[1] = p2;

returned = base.ExecuteStoreQuery<YourClass>("exec your_stored_proc_name @p1, @p2", parameters);

【问题讨论】:

    标签: .net stored-procedures entity poco


    【解决方案1】:

    是的,你可以使用the generic version of ExecuteStoreQuery 一次get to the ObjectContext

    var listOfType= ((IObjectContextAdapter)context).ObjectContext
                        .ExecuteStoreQuery<Type>("SPROCNAME");
    

    Here is the MSDN sample code (just change the TSQL to a sproc)

    And, here is one that shows how to deal with parameters

    较新版本的EF有SqlQueryDbContext.Database to get the ObjectContext easier

    var listOfType = context.Database.SqlQuery<Type>("SPROCNAME");
    

    【讨论】:

    • @MystereMan 已更新,抱歉 :)
    • 这似乎至少需要SqlQuery&lt;Type&gt;("EXEC SPROCNAME")。如果你的 sproc 有参数,你也必须将它们包含在你的 SQL 语句中。
    猜你喜欢
    • 1970-01-01
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 2012-03-08
    • 2016-10-03
    • 1970-01-01
    相关资源
    最近更新 更多