Please enable Javascript for better experience...
How to ignore a class property in Dapper.net
By Rahul Kumar Jha | Feb 13, 2015 | In Tips | Total Views [ 16842 ]
(2 Like)
Rate

In dapper you can ignore a property in model class using [DapperAttribute.Computed] attribute. Let's see how to do this.

The Problem

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.

A quick solution

In Dapper you can use [DapperAttribute.Computed] attribute to achieve this. Let's see this with an example.

Database Structure

Create a table and name it People. Below is the table structure for people table.

The Model

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.

Share this

About the Author

Rahul Kumar Jha
Rahul Kumar Jha
Founder, Developer dotnet-concept.com

Public profile: user/profile/99900001


Has working experience in different phases of Software Development Life Cycle (SDLC) in CMS, Gaming, Health Care and Financial Services domain using Agile pattern. Working experience in Design patterns, ASP.NET, MVC, ANGULAR, ANGULAR JS, Windows application, WCF, ADO.NET, SQL Server and Test Driven Development (TDD) environment with JQuery, JavaScript, N-Unit, Entity Frameworks, LINQ, Code Refactoring and Business Objects Models.

User's Comments


 
Please SignUp/Login to comment...

Or comment as anonymous...
* Name
* Email ID
Comment
 
 
 
 
 
 
Sponsors