Click here to Skip to main content
15,897,187 members
Please Sign up or sign in to vote.
1.44/5 (2 votes)
hi to all,
Kindly help me how to validate unique key here i'm using this code in modal

[Index(IsUnique = true)]
[Required(ErrorMessage = "Branch Code is required.")]
[RegularExpression(@^[a-zA-Z0-9'' ']+, ErrorMessage =Special characters ( ,@/)(=][|\!`’%$#^”&* ) are not allowed in the name.)]
[StringLength(3)]
[Column(TypeName = char)]
public string Branch_Cde { get; set; }

if i give same Branch code then it will occur exception. how to validate above unique key.
Posted
Comments
jo.him1988 16-Jul-14 2:14am    
you have to check it by code because its needed database Existance so if you have textbox write event to validate the branch code
Sergey Alexandrovich Kryukov 16-Jul-14 2:32am    
Why? Normally, developers don't validate uniqueness but instead generate unique key in first place...
—SA
JOTHI KUMAR Member 10918227 16-Jul-14 2:36am    
thanks for reply. i'm new for mvc 5 so kindly explain me detail

1 solution

You need a "Base Model" from where you will inherit the unique ID.

C#
public  class BaseModel<t> where T : BaseModel<t>
{
    [Key, Required, DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    // You can do a lot of very useful code here...
}


C#
public class PersonModel : BaseModel<personmodel>
{
    public string Name { get; set; }
    public DateTime Birth{ get; set; }
}


And of course add it to your entityframework context

C#
public class SMSServiceContext : DbContext
{
    public SMSServiceContext()
    : base()
    {
    
    }

    public DbSet<personmodel> PersonModels{ get; set; }
    // Add other tables here...
    
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }


The unique Key will be automatic and unique. This is how I do it when I work with entityframework anyways.

I hope I answered your question. If not, please inform me :)
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900