Verifying Duplication

Back to Examples


If you haven't already, please take a look at the [DuplicationColumn] attribute.

Evaluation for duplication is done through the DuplicationColumnAttribute class and the IsDuplicated() method.

Basically, the IsDuplicated() method evaluates that for a specific table there is at least a row that has the same values for the designated columns (properties decorated with the [DuplicationColumn] attribute) with a different key than the entity invoking the method.

You may use the IsDuplicated() method to evaluate all duplication groups individually or altogether depending what you need for your application.

Below an example on how to use the IsDuplicated() method.

using System;
using MagnaDB.SqlServer;

namespace TestMagnaDB
{
    public class Cat : TableModel<Cat>
    {
        protected override string ConnectionString => "Data Source=testmagna.db;New=True;Version=3;";
        protected override string TableName => "Cats";
        protected override MagnaKey Key => this.MakeKey(cat => cat.Id);

        [Identity]
        public long Id { get; set; }
        
        [DuplicationColumn]
        public string Name { get; set; }
        
        [DuplicationColumn]
        public string Breed { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Cat newcat = new Cat() { Name = "Olivia", Breed = "Calico" };

            // This will verify that there if there's
            // another row in the table with the same Name and Breed,
            // behavior we defined by previously decorating those properties
            // with the [DuplicationColumn] attribute
            if (newcat.IsDuplicated())
            {
                Console.WriteLine("That kitten already exists in the database");
            }
            else
            {
                newcat.Insert();
            }
        }
    }
}