实体框架如何防止重复条目进入数据库 [英] Entity framework How to prevent duplicate entries into db

查看:73
本文介绍了实体框架如何防止重复条目进入数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用EntityFramework将项目版本号保存到数据库
中。在UI页面上,用户键入version(major,Minor,Build)整数值,然后单击保存按钮
。在保存之前,我希望确保不会在数据库中创建任何重复的版本。

I am using EntityFramework to save a project version number to database .On the UI page user types in version(major,Minor,Build) integer values and click save button Before I save ,I want to ensure that no duplicate version is getting created in the DB.

我要尝试的是确保major.minor.build组合是唯一的

what I am trying is to make sure that major.minor.build combination is unique

ProjVersion newVersion=new ProjVersion ();
newVersion.Major=10;
newVersion.Minor=1;
newVersion.Build=1;
this.repository.Add<ProjVersion>(newVersion);
//here how can I ensure that no duplicate versions are added to database
 this.repository.SaveChanges();

[Serializable]
    public class ProjVersion 
    {
        [Key]
        public int Version_Id { get; set; }
        public int Major { get; set; }
        public int Minor { get; set; }
        public int Build { get; set; }
    }


推荐答案

检查是否有数据库中与您要添加的内容具有相同详细信息的条目。如果不是,那么它是一个新版本,应该添加它;如果是这样,则它是重复版本,您应该做任何您想处理的情况。

Check if there are any entries in the database that have the same details as what you're trying to add. If not, then it's a new version and you should add it, if so then it's a duplicate and you should do whatever you want to handle that situation.

if (repository.Get(x => x.Major == newVersion.Major && 
    x.Minor == newVersion.Minor && x.Build == newVersion.Build)
    .Count() > 0)
{
     //notify the user that they are making a duplicate entry
}
else
{
     repository.SaveChanges();
}

这篇关于实体框架如何防止重复条目进入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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