AliCa
AliCa

Reputation: 269

How to specify a Schema while mapping with DapperExtensions?

I'm trying to get all records from SQL database using DapperExtensions.

But I have a Schema set to other than dbo for some tables. Hence, the table is not recognized from sql query.

For example, a table is in the form [Schema][TableName]. But when I start query, error is thrown like:

Invalid object name 'TableName'.

This is the Model class:

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
    {

This is the function to GetAll records from database:

public async Task<IReadOnlyList<City>> GetAllAsync()
        {
            var CityList = await Context.Connection.GetListAsync<City>();
            Context.Connection.Close();
            return CityList.ToList();
          
        }

Upvotes: 2

Views: 1435

Answers (1)

Amit Joshi
Amit Joshi

Reputation: 16389

While mapping your models, be bit more explicit. Mention the Schema explicitly.
Following is an example how to provide various mapping properties.

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();
    }
}

Please note that, if your column names and property name in model is same, you do not need to call Map for each property (the way I did above Map(x => x.CustomerID).Key(KeyType.Identity);). Instead, only call AutoMap(); and properties will be automatically mapped.

To make these mappings known to Dapper Extensions, call the following code only once at application startup:

DapperExtensions.DapperExtensions.SetMappingAssemblies(new[] { Assembly.GetExecutingAssembly() });

Upvotes: 2

Related Questions