Skip to content

Use case: Custom map between model property and table column using ModelToTableMapper T

christiandelbianco edited this page Jun 21, 2017 · 4 revisions

When model has properties with different name from table's column, we can use ModelToTableMapper for mapping:

Assuming a database table as:

CREATE TABLE [Customers] (
	[Id] [int] IDENTITY(1, 1) NOT NULL,
	[First Name] [varchar](50) NULL,
	[Last Name] [varchar](50) NULL)

Assuming a C# model as:

    public class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
    }

In order to receive notifications containing record's values changed, inserted or deleted, the following code can be used:

var mapper = new ModelToTableMapper<Customer>();
mapper.AddMapping(c => c.Name, "First Name");
mapper.AddMapping(c => c.Surname, "Last Name");

var tableName = "Customers";
var tableDependency = new SqlTableDependency<Customer>(connectionString, tableName, mapper);
tableDependency.OnChanged += TableDependency_Changed;
tableDependency.Start();

This setting override Code First Data Annotations.

Clone this wiki locally