Get Stored Procedure from Data Context : Linq to SQl

前端 未结 3 1152
旧时难觅i
旧时难觅i 2020-12-21 06:34

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.

相关标签:
3条回答
  • 2020-12-21 06:51

    It's a pretty huge break of SOC to have any callers of your repository be aware of whether or not a particular method call results in reading text from a file, SQL statement, sprocs or even just garden gnomes typing results out on a text terminal.

    To that end, it doesn't help matters to have your Context property be public. The whole point of using a repository is so that consumers are shielded from persistence concerns!

    Since you seem to have a strong need to avoid using a custom-typed Context, you'd save yourself much trouble and just issue a straight-up, old-school SQL statement that will execute your sproc.

    Consider refactoring your interface and logic to look more like this:

    public interface ILijosBankRepository
    {
        List<DBML_Project.BankAccount> GetAllAccountsForUser(int userID);
        void UpdateBankAccount(/* params go here */);
        /* ...other query methods, etc... */
    
    }
    public class LijosBankRepository : ILijosBankRepository
    {
         private readonly DataContext context { get; set;}
         public LijosBankRepository(DataContext ctx) { ... }
    
         public void UpdateBankAccount(string inputXml)
         {
              context.ExecuteCommand("ParseXML", inputXml);
         }
    
    }
    
    0 讨论(0)
  • 2020-12-21 07:00

    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);
    
    0 讨论(0)
  • 2020-12-21 07:04

    The C# wrapper is part of your custom DataCcontext derived class. You would call like this:

    public virtual void UpdateBankAccountUsingStoredProcedure()
    {
        var results = Context.ParseXML(...);
        ...
    }
    
    0 讨论(0)
提交回复
热议问题