问题描述
我在 sql server 中有一个名为 parsexml 的存储过程.我有一个使用 linq to sql 的存储库模式.我需要从存储库层中调用存储过程.与 gettable 方法不同,我们没有用于数据上下文的 getstoredprocedure 方法.这种情况下如何调用存储过程?
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?
数据库代码
[global::system.data.linq.mapping.functionattribute(name="dbo.parsexml")] public isingleresultparsexml([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 )(result.returnvalue)); }
存储层
namespace repositorylayer { public interface ilijosbankrepository { system.data.linq.datacontext context { get; set; } listgetallaccountsforuser(int userid); void updatebankaccountusingstoredprocedure(); } public class lijossimplebankrepository : ilijosbankrepository { public system.data.linq.datacontext context { get; set; } public list getallaccountsforuser(int userid) { iqueryable queryresultentities = context.gettable ().where(p => p.accountownerid == userid); return queryresultentities.tolist(); } public virtual void updatebankaccountusingstoredprocedure() { //context.getstroedprocedures(); } } }
参考:
- 多个 unitofworks、isession 和存储库
推荐答案
让存储库的任何调用者知道特定方法调用是否导致从文件、sql 读取文本是 soc 的一个巨大突破语句、sprocs 甚至只是花园侏儒在文本终端上输入结果.
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.
为此,将 context 属性设为公开无济于事.使用存储库的全部意义在于让消费者免受持久性问题的困扰!
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!
由于您似乎非常需要避免使用自定义类型的 context,您可以省去很多麻烦,只需发出一个直接的、老式的 sql 语句即可执行你的程序.
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 { listgetallaccountsforuser(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); } }