我使用 SQL CE 还是 SQL Server 实体框架?
我将 EF 与 2 个数据库一起使用 - SQL CE 和 SQL Server。
有没有办法知道运行时使用哪种连接类型?我的意思是,如果我在某个地方只有 ObjectContext(已使用某些连接字符串初始化),我可以从中获取数据库类型(目前是 Compact 还是 SQL Server)吗?
谢谢
I'm using EF with 2 databases - with SQL CE and SQL Server.
Is there a way to know which connection type is used at runtime? I mean, if I have only ObjectContext in some place (already initialized with some connection string), can I get the database type from it (is it Compact or SQL Server at the moment)?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以检查连接属性,它应该返回 EntityConnection;从那里您必须检查其 StoreConnection这将是“真正的”数据库连接。
从那里,您可以检查 ConnectionString,它会告诉您提供者,或者只需使用
is
或GetType
检查提供者连接本身的类型。如果是 SQL Server,则为SqlConnection
,如果是 SQL CE,则为SqlCeConnection
。这看起来像是一个丑陋的黑客行为,因为它确实如此;如果您正在寻找一种无需丑陋的黑客手段来实现此目的的方法,请不要打扰 -
ObjectContext
已明确设计不会泄漏有关连接的任何信息,除非您确切知道要询问什么。相比之下,这里是您必须跳过的所有环节才能通过应用程序配置进行检查:一旦任何解决方案开始涉及正则表达式,我倾向于寻找更直的路径,在这种情况下,这就是您所说的类型转换宁愿不使用。选择你的毒药。
使用上述任一方法时请务必小心。 EF4 是围绕持久性无知而设计的,您应该尝试避免任何特定于连接类型的逻辑,因为您真的不知道它将如何配置(也许明天它将是 Oracle 连接) 。我相信特定于提供程序的代码主要驻留在 查询提供者。
You can check the Connection Property, which should return an EntityConnection; from there you must check its StoreConnection which will be the "real" database connection.
From there, you can either check the ConnectionString, which will tell you the provider, or simply check the type of the provider connection itself with
is
orGetType
. If it's SQL Server it will be aSqlConnection
, and if it's SQL CE it will be aSqlCeConnection
.This looks like an ugly hack because it is; if you're looking for a way to do this without an ugly hack, don't bother - the
ObjectContext
is explicitly designed not to leak any information about the connection unless you know exactly what to ask for. By contrast, here's all the hoops you would have to jump through to check it via the app config:Once any solution starts to involve regexes, I tend to look for a straighter path, and in this case, that's the type casting you say you'd prefer not to use. Pick your poison.
Be careful how you use either of the above approaches. EF4 is designed around persistence ignorance and you should be trying to avoid any logic that's specific to the connection type, because you really have no idea how it will be configured (maybe tomorrow it will be an Oracle connection). I believe that the provider-specific code resides mainly in the QueryProvider.