0

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?

8
  • what is the relationship First : Second ? Commented Sep 19, 2016 at 14:53
  • @Sampath Every instance of Second has an instance of First. As for database I have two tables: First and Second. And Second has a foreign key to Id in table First Commented Sep 19, 2016 at 14:57
  • is that mean 1:1 ? Commented Sep 19, 2016 at 15:19
  • what is this GetData() ? Commented Sep 19, 2016 at 15:21
  • @Sampath no 1 : many. GetData is some abstract method that returns List<Second> Commented Sep 19, 2016 at 15:37

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.