Entity framework How to prevent duplicate entries into db

霸气de小男生 提交于 2020-02-05 14:00:26

问题


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.

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

回答1:


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();
}



回答2:


It sounds like you need to use a Compound Key, where all properties (columns) are part of the Primary Key.

{
    [Key, Column(Order = 0)]
    public int Major { get; set; }

    [Key, Column(Order = 1)]
    public int Minor { get; set; }

    [Key, Column(Order = 2)]
    public int Build { get; set; }
}

Attempts to insert records with matching keys will produce an Exception.



来源:https://stackoverflow.com/questions/18538859/entity-framework-how-to-prevent-duplicate-entries-into-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!