简体   繁体   English

实体框架 - 使用默认参数调用存储过程

[英]Entity Framework - Call stored procedure with default parameters

I have some stored procedures mapped in Entity Framework using Database First. 我使用Database First在Entity Framework中映射了一些存储过程。 It creates strongly typed methods that you can call to run the stored procedures. 它创建强类型方法,您可以调用它们来运行存储过程。 I've run into a significant problem, however, in that I don't see any way to call these methods it created with the default parameters defined in the stored procedures. 但是,我遇到了一个重大问题,因为我没有看到任何方法来调用它使用存储过程中定义的默认参数创建的这些方法。 This means: 这意味着:

a) I have to manually add the default parameters to the method calls, which is brittle, if the default parameter value were to ever change. a)如果默认参数值要改变,我必须手动将默认参数添加到方法调用中,这是脆弱的。

b) Write method overloads by hand. b)手动写入方法重载。 This basically eliminates the benefit of generating a model from the database in the first place. 这基本上消除了首先从数据库生成模型的好处。

Does anyone know if there is a better solution to this problem? 有谁知道这个问题是否有更好的解决方案?

Thanks. 谢谢。

As of Jan 2013, there's no supported way to do have the Entity Framework do this. 截至2013年1月,实体框架没有支持的方法可以做到这一点。

I have opened a feature request here . 在这里打开了一个功能请求。

Here's a hacky workaround. 这是一个hacky解决方法。 I don't know if there's a feature in EF to support optional parameters, but you can try to emulate it - if you're willing to change the stored procedures. 我不知道EF中是否有支持可选参数的功能,但您可以尝试模拟它 - 如果您愿意更改存储过程。

You can change the default value in the definition of the stored procedure to NULL , and then in the body of the procedure, replace NULL parameters with the desired default value. 您可以将存储过程的定义中的默认值更改为NULL ,然后在过程的主体中,将NULL参数替换为所需的默认值。 Then from the code using EF you could pass null to indicate using the default. 然后从使用EF的代码中,您可以传递null以指示使用默认值。 This way at least the default is only defined in the SP itself. 这样,至少默认值仅在SP本身中定义。

Drawbacks include of course that now NULL becomes an "out-of-band" value, meaning you can't actually pass it to the SP if that's what you need (besides having to change your SPs and ensuring all future ones use this weird convention) 缺点当然包括现在NULL成为“带外”值,这意味着如果你需要的话,你实际上不能将它传递给SP(除了必须改变你的SP并确保所有未来的人都使用这个奇怪的约定)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM