实体框架如何防止重复条目进入数据库

实体框架如何防止重复条目进入数据库

问题描述:

我正在使用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();
}