无效的对象名称dbo.TableName“从产生在检索表数据时 [英] Invalid object name 'dbo.TableName' when retreiving data from generated table

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

问题描述

我使用实体框架code先创造我的表。请注意 - 创建表,而不是数据库,因为我工作的一个托管环境,我没有被允许创建数据库的用户

提交一个数据库的更新工作正常,但在检索​​数据给出了异常:

  

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

我读过,这是因为我没有使用EF code首先创建数据库。这很好,但我如何优雅地解决这个问题?

所有生成的表没有preFIX像DBO。像这样的解决方案不起作用,而不是优雅可言:

  [表(EventHosts模式=)]
 

解决方案

要回答你的第一个问题:你的托管服务提供商使用,为你创建的模式

要回答你的第二个问题:没有,目前还没有直接的方式在全球范围内更改默认模式,因为你不能修改现有公约或创建新的公约。你可以尝试破解它。

例如,你可以覆盖 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 retreiving 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天全站免登陆