当从生成的表中检索数据时,对象名称“dbo.TableName”无效 [英] Invalid object name 'dbo.TableName' when retrieving data from generated table

查看:1204
本文介绍了当从生成的表中检索数据时,对象名称“dbo.TableName”无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先使用实体​​框架代码来创建我的表。请注意 - 创建表,而不是DB,因为我正在处理托管环境,而且我没有允许创建数据库的用户。



提交数据库更新工作正常,但检索数据提供了例外:


异常详细信息:System.Data.SqlClient.SqlException:无效的对象名称'dbo.EventHosts'。


我已经阅读了,因为我没有使用EF Code First创建数据库。没问题,但是如何优雅地解决这个问题?



所有生成的表都没有像dbo这样的前缀。这样的解决方案不起作用,根本不优雅:

  [Table(EventHosts,Schema = )] 


解决方案

回答你的第一个问题:您的主机提供商为您创建的模式。



回答您的第二个问题:目前没有直接方法来全局更改默认模式,因为您无法修改现有约定或创建新的约定。您可以尝试将其删除。



例如,您可以覆盖 OnModelCreating 并使用反射来获取所有 DbSet<> 在您的上下文中声明的属性。您可以使用这些属性上的简单循环,并创建 ToTable 映射调用,该属性名称作为表名称和自定义模式。这将需要一些反思来使这项工作。



或者,您可以尝试通过实现自定义约定来做一些可重用的方法。您可以找到许多有关使用自己的约定与EF的不同的文章。一些例子:





我的高级未经测试的想法遵循相同的原则,并创建程序集属性,将由常规机制处理并应用于所有实体。


I'm using entity framework code first to create my tables. Please note - create the tables, not the DB, since I'm working on a hosted environment and I don't have a user that is allowed to create db's.

Committing a DB update works fine, but retrieving data gives the exception:

Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'dbo.EventHosts'.

I've read that it happens because I'm not using EF Code First to create the DB. That's fine, but how do I elegantly solve this?

All the generated tables do not have a prefix like dbo. A solution like this doesn't work, and isn't elegant at all:

[Table("EventHosts", Schema = "")]

解决方案

To answer your first question: use the schema created for you by your hosting provider.

To answer your second question: No there is currently no direct way to change the default schema globally because you cannot modify existing conventions or create new conventions. You can try to hack it.

For example you can override OnModelCreating and use reflection to get all DbSet<> properties declared in your context. Than you can just use simple loop on these properties and create ToTable mapping call with name of the property as table name and your custom schema. It will require some playing with reflection to make this work.

Alternatively you can try to do some reusable approach by implementing custom conventions. You can find many different articles about using your own conventions with EF. Some examples:

My high level untested idea is following same principle and create assembly level attribute which will be processed by the convention mechanism and applied on all your entities.

这篇关于当从生成的表中检索数据时,对象名称“dbo.TableName”无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆