我正在尝试使用 DapperExtensions 从 SQL 数据库获取所有记录。
但对于某些表,我将架构设置为 dbo
以外的模式。因此,sql 查询无法识别该表。
例如,表的格式为[Schema][TableName]
。但是当我开始查询时,会抛出错误,如下所示:
Invalid object name 'TableName'.
这是模型类:
using System;
using Dapper.Contrib.Extensions;
using ImOnTech.Teftis.Core.Models;
using ImOnTech.Teftis.Core.Models.DT_Inspection;
namespace ImOnTech.Teftis.Core.Models.DT_Inspection
{
[Table("DT_Inspection.City")]
public class City
{
这是从数据库中GetAll
记录的函数:
public async Task<IReadOnlyList<City>> GetAllAsync()
{
var CityList = await Context.Connection.GetListAsync<City>();
Context.Connection.Close();
return CityList.ToList();
}
最佳答案
在映射模型时,要更明确一些。明确提及架构
。
以下是如何提供各种映射属性的示例。
public class Customer
{
public int CustomerID { get; set; }
public string Name { get; set; }
}
public sealed class CustomerMapper : ClassMapper<Customer>
{
public CustomerMapper()
{
Schema("dbo");
Table("Customer");
Map(x => x.CustomerID).Key(KeyType.Identity);
AutoMap();
}
}
请注意,如果模型中的列名称和属性名称相同,则无需为每个属性调用 Map
(就像我上面所做的那样 Map(x => x.CustomerID).Key(KeyType.Identity);
)。相反,只需调用 AutoMap();
,属性就会自动映射。
要使 Dapper 扩展了解这些映射,只需在应用程序启动时调用以下代码一次:
DapperExtensions.DapperExtensions.SetMappingAssemblies(new[] { Assembly.GetExecutingAssembly() });
关于c# - 如何在使用 DapperExtensions 映射时指定 Schema?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68363594/