【问题标题】:Using Reflection to get Stored Procedure name from Entity Data Model.使用反射从实体数据模型中获取存储过程名称。
【发布时间】:2012-01-27 21:34:39
【问题描述】:

假设我已经构建了 DAL.dll,它是一个包含实体框架 edmx 的类库。在 Designer.cs 中,定义了以下导入的存储过程:

    <Function Name="Login_User" Aggregate="false" BuiltIn="false" NiladicFunction="false" IsComposable="false" ParameterTypeSemantics="AllowImplicitConversion" Schema="dbo">
      <Parameter Name="Login_Name" Type="nvarchar" Mode="In" />
      <Parameter Name="Password" Type="nvarchar" Mode="In" />
      <Parameter Name="SP_Return_Code" Type="int" Mode="InOut" />
    </Function>

下面我使用反射找到 type1 作为 ObjectContext 类型。如何通过反射type1发现Login_User存储过程?

    private static void ReflectionTest()
    {
        var asm = Assembly.LoadFrom(@"C:\DAL.dll");

        // list stored procedure calls
        foreach (var type in asm.GetTypes())
        {
            if (type.BaseType == typeof(ObjectContext))
            {
                foreach (var type1 in type.GetMethods())
                {
                    // how do I reflect against type1 for its stored procedure names?
                }
            }
        }
    }

【问题讨论】:

  • 你为什么要为此使用反射?

标签: c# .net entity-framework reflection stored-procedures


【解决方案1】:
  1. 首先,您需要在实体模型中将存储过程导入为Function。请参阅此链接了解操作方法:http://ashishrocks.wordpress.com/2010/09/05/entity-framework-using-select-stored-procedures-for-entities-having-same-column-names/

  2. 在您执行此操作时,请确保为您的Function Import Name 使用某种命名约定。例如,为所有存储过程函数导入添加前缀 SP_

  3. 将 SP 作为函数添加到实体模型中后,您应该能够在 Model.Designer.cs 中看到它们。编译更新的 DAL。

现在你可以像这样得到你的存储过程:

Assembly assembly = Assembly.LoadFrom(@"C:\DAL.dll");

foreach (MethodInfo methodInfo in from type in assembly.GetTypes()
                                  where type.BaseType == typeof (ObjectContext)
                                  from methodInfo in type.GetMethods()
                                  where methodInfo.Name.StartsWith("SP_")
                                  select methodInfo)
{
    Console.WriteLine(methodInfo.Name);
}

Console.ReadLine();

【讨论】:

    猜你喜欢
    • 2015-11-15
    • 2018-05-25
    • 2012-12-10
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多