Get Stored Procedure from Data Context : Linq to SQl

こ雲淡風輕ζ 提交于 2019-11-29 15:10:31

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

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

}

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

public virtual void UpdateBankAccountUsingStoredProcedure()
{
    var results = Context.ParseXML(...);
    ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!