I'm using Entity Framework 4.4 and I have a One-To-Many relationship model like this:
class A {
public int Id { get; set; }
public virtual B { get; set; }
public int BId;
}
class B {
public Id { get; set; }
private ICollection<A> _As;
public virtual ICollection<A> As
{
get { return _As ?? (_As = new HashSet<A>()); }
protected set { _As = value; }
}
}
Now, supposing I have 2 A instances, both with the same B instance. Then I'd have something like this (JSON representation):
A: { Id: 1, BId: 1, B: { Id: 1, As: [ 1, 2 ] } }
A: { Id: 2, BId: 1, B: { Id: 1, As: [ 1, 2 ] } }
I want to then cycle through my current list of A instances and add the to the db context:
foreach (var a in LocalAList)
{
dbContext.Add(a);
dbContext.SaveChanges();
}
The problem is that I get exceptions informing me that I've inserted duplicate objects. I've looked around and found things dealing with Entity modification and attachment, but I'm still pretty new to EF. I would imagine that this is a typical thing and there's an idiom for handling object insertion where the object already exists.
How can I efficiently add new objects to the context while avoiding the addition of duplicates? Should I just capture the duplicate exception and ignore it? Is there a better way to check?
Ids database generated identities? And what exception do you get exactly? An exception about a primary key constraint violation? (In that case you can't have database generated identities, I think...) What do you want to insert exactly? Only theAs, or theBs as well? Or are theBs existing entities and you want only to create a relationship between newAs and existingBs?