如何从不在默认DBO模式中的SQL Server数据库表中读取数据
•浏览 1
How to read data from SQL server database table that is not in the default DBO schema
我正在构建一个使用 SQL Server 作为数据库的 .NET MVC 4 应用程序,我使用 Dapper 和 Dapper SimpleCRUD 进行数据库操作。在我的数据库中,我在默认 dbo 模式中有表,并且在其他模式中也有表,比如 product.clients 而不是 dbo.clients。我在 SQL 服务器上创建了一个单独的登录名,该登录名映射到数据库上的一个单独的用户帐户(产品架构的所有者,默认为产品架构)。但是使用此凭据连接到数据库会给我诸如 System.Data.SqlClient.SqlException:无效的对象名称 \\'clients\\' 之类的异常。现在,我已经搜索和搜索,但找不到如何在 web.config 中构造正确的连接字符串元素,以便我可以从默认 dbo 以外的模式中读取数据。我该怎么做?
您可以在查询中明确指定模式名称
SELECT Id,ClientName FROM product.clients
SELECT C.Id,C.ClientName FROM product.clients C WITH (NOLOCK)
INNER JOIN dbo.UserAccount U WITH(NOLOCK)
ON U.UserId=C.CreatedById
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Dapper;
namespace MyApp.Models
{
[Table("Clients", Schema="Products")]
public class Client
{
public int id { get; set; }
public string firstname { get; set; }
public string lastname { get; set; }
}
}
只要 sql 用户有权访问架构,它就应该可以工作。
您可以根据需要从 2 个 schamas 连接表格。
SELECT Id,ClientName FROM product.clients
SELECT C.Id,C.ClientName FROM product.clients C WITH (NOLOCK)
INNER JOIN dbo.UserAccount U WITH(NOLOCK)
ON U.UserId=C.CreatedById
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Dapper;
namespace MyApp.Models
{
[Table("Clients", Schema="Products")]
public class Client
{
public int id { get; set; }
public string firstname { get; set; }
public string lastname { get; set; }
}
}
好的,解决方案很简单,但不明显,除非你知道去哪里找。也许我的 google-fu 不是很好。
答案是可以在Table属性注解中定义schema。
SELECT Id,ClientName FROM product.clients
SELECT C.Id,C.ClientName FROM product.clients C WITH (NOLOCK)
INNER JOIN dbo.UserAccount U WITH(NOLOCK)
ON U.UserId=C.CreatedById
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Dapper;
namespace MyApp.Models
{
[Table("Clients", Schema="Products")]
public class Client
{
public int id { get; set; }
public string firstname { get; set; }
public string lastname { get; set; }
}
}
这将有助于 Dapper 和 Dapper SimpleCRUD 找到正确的表并从那里读取数据。
https://msdn.microsoft.com/en-us/library/system.data.linq.mapping.tableattribute(v=vs.110).aspx