In dapper you can ignore a property in model class using [DapperAttribute.Computed] attribute. Let's see how to do this.
Sometime you need to add few extra properties in your model which do not match with database columns. You will get a "Invalid column" error when trying to insert records in database. Somehow you need to find a way so that these properties can be ignored while performing insert or other such operation. Let's see how to resolve this problem.
In Dapper you can use [DapperAttribute.Computed] attribute to achieve this. Let's see this with an example.
Create a table and name it People. Below is the table structure for people table.
Create a model for above table.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using DapperAttribute = Dapper.Contrib.Extensions;
namespace MyTestProject
{
[DapperAttribute.Table("People")]
public sealed class Person
{
[DapperAttribute.Key]
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailID { get; set; }
public DateTime CreatedDate { get; set; }
public Boolean IsActive { get; set; }
public string FullName { get; set; }
}
}
If you notice, property FullName is not there in People table and it will through error while perform insert operation. To overcome this we need to find a way so that this property can be ignored while insert. To do this simply add [DapperAttribute.Computed] attribute on FullName.
[DapperAttribute.Computed]
public string FullName { get; set; }
And you are done. Hope this can help you. I will come up with more such tips in future.