如何避免MVC在数据库中记录冗余数据 [英] How to avoid recording redundante data in database by MVC

查看:70
本文介绍了如何避免MVC在数据库中记录冗余数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个有两个属性的类(名字,系列)。

我已经编写了将数据插入数据库的代码而没有问题,但我不知道怎么写代码

检查数据是否已经存在或者?

任何人都可以指导我吗?



我需要MVC 4或更高版本的样本。



感谢先进的

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

推荐答案

makename字段独特。保存新项目之前



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

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
           }
       }


您可以为名称或名称和家庭创建主键(取决于您的要求)

当您有主键时,您不能插入重复值。插入时会出现异常。使用试试..赶上 [ ^ ]您可以检查数据是否已存在。
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.


这篇关于如何避免MVC在数据库中记录冗余数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆