Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

c# - Get Stored Procedure from Data Context : Linq to SQl

I have a stored procedure named ParseXML in SQL Server. I have a repository pattern using LINQ to SQL. I need to call the stored procedure from within the repository layer. Unlike GetTable method, we don’t have a GetStoredProcedure method for data context. How can we call the stored procedure in such a scenario?

Dbml Code

[global::System.Data.Linq.Mapping.FunctionAttribute(Name="dbo.ParseXML")]

    public ISingleResult<ParseXMLResult> ParseXML([global::System.Data.Linq.Mapping.ParameterAttribute(Name="InputXML", DbType="Xml")] System.Xml.Linq.XElement inputXML)
    {
        IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), inputXML);
        return ((ISingleResult<ParseXMLResult>)(result.ReturnValue));
    }

Repository Layer

namespace RepositoryLayer
{
public interface ILijosBankRepository
{
    System.Data.Linq.DataContext Context { get; set; }
    List<DBML_Project.BankAccount> GetAllAccountsForUser(int userID);
    void UpdateBankAccountUsingStoredProcedure();

}

public class LijosSimpleBankRepository : ILijosBankRepository
{
    public System.Data.Linq.DataContext Context
    {
        get;
        set;
    }


    public List<DBML_Project.BankAccount> GetAllAccountsForUser(int userID)
    {
        IQueryable<DBML_Project.BankAccount> queryResultEntities = Context.GetTable<DBML_Project.BankAccount>().Where(p => p.AccountOwnerID == userID);
        return queryResultEntities.ToList();
    }


    public virtual void UpdateBankAccountUsingStoredProcedure()
    {
        //Context.GetStroedProcedures();
    }

}

}

REFERENCE:

  1. Multiple UnitOfWorks, ISession and repositories
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do something like this, calling the method using reflection:

var inputXML = GetXML(); 

var method = Context.GetType().GetMethod("ParseXML");

if(method == null) throw new InvalidOperationException("Defined DataContext does not have method ParseXML");

var result = method.Invoke(Context, new object[]{ inputXML });

If you are using c# 4.0, you can do:

var inputXML = GetXML(); 

dynamic dynamicContext = Context;

var result = (ISingleResult<ParseXMLResult>)dynamicContext.ParseXML(inputXML);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...