Click here to Skip to main content
15,889,861 members
Please Sign up or sign in to vote.
2.60/5 (2 votes)
See more:
Hi,
I have a class with two properties (name,family).
I have wrote code for insert data into database without problem,but I dont know how to write code
for check the data is already exists or ?
anybody can guid me?

I needs sample for MVC 4 or higher.

Thanks in advanced
Posted

make "name" field unique. and before saving the new item

C#
public int AddProject(Project OProject)
       {
           var context = new DbSysEntities1();

           var original = (from p in context.Project
                          where p.ProjectName == OProject.ProjectName
                          select p).FirstOrDefault();
           if (original == null)
           {
              context.Project.Add(OProject);
              if (context.SaveChanges() > 0)
               return 0; //success
              else
               return 1; //error
           }
           else
           {
                return 2; //already exist
           }
       }
 
Share this answer
 
v6
Comments
sorosh04 9-May-14 15:59pm    
Getting error from this line : var original = context.Project.Find(OProject.Name);

Its unhandle error and nothing else for figour out whats the resoan
Vi(ky 9-May-14 16:05pm    
sorry, its my mistake. "Find" works with primary key
Vi(ky 9-May-14 16:03pm    
please check my update solution
you can create primary key for name or both name and family ( depending on your requirements)
When you have primary key, you can't insert duplicate values. You will get exception when inserting. using try.. catch[^] you can check the data already exist or not.
 
Share this answer
 
v2
Comments
sorosh04 9-May-14 15:35pm    
How can I handle exceptions?
Its not better to select on table and compared with the textbox that user filled out and then decide its redundante data or not ?
DamithSL 9-May-14 15:41pm    
then you need to call database twice in case of new record.

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