简体   繁体   中英

Entity Framework and duplicates

I use Entity Framework as ORM in my project. Let's suppose I use Code-First pattern and I have two models. Such as

internal class First
{        
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int  Id { get; set; }

    public string Name { get; set; }
}

internal class Second
{        
    public int  Id { get; set; }

    public First ForeignKeyEntity { get; set; }

    // other members
}

And here is code populating database:

List<Second> res = GetData();
using (var ctx = new StatisticContext())
{
    foreach (var item in res)
    {
        ctx.Seconds.Add(item);
    }
    ctx.SaveChanges();
}

As you can see each instance of class Second has instance of class First in its member ForeignKeyEntity . Obviously some instances of First can be duplicated in res. And when I run this code I get DbUpdateException in ctx.SaveChanges() with inner exception that has the following message:

Violation of PRIMARY KEY constraint 'PK_dbo.First'. 
Cannot insert duplicate key in object 'dbo.First'. 
The duplicate key value is (29459). The statement has been terminated.

I can not to insert duplicated rows but I don't want to insert duplicates, I would like to insert row only if it doesn't exist. How to solve this problem? How to insert foreign key object only if doesn'tt exist?

The normal way of doing things would be to do a read first with item to see if it exists. If it does then you need to use ctx.Seconds.Update(item);

If your items are already on the context, then you can check the state. it will be either State.Modified or State.Added .

Whats in GetData()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM