When possible, try to link objects in EF to each other by setting Navigation properties. After all, EF is an
Object Relationship Mapper :)
In order to check if a 'related' entity exists already in the database context (to maintain relationship integrity), you are going to have to do some sort of lookup. Use the objects!
This approach works fine for a few hundred objects at a time - but remember EF isn't designed for high volume updates/inserts. If you need maximum throughput, drop back to using underlying ADO.Net classes such as SqlDataReaders or SQLBulkCopy etc.
Below demonstrates how I would approach the situation.
using (var db = myDbContext)
{
var batch = db.Batches.SingleOrDefault(b => b.BatchNumber == handShake.Batch);
if (batch == null)
{
batch = new Batch()
{
};
}
foreach (Product product in products)
{
BatchProduct batchproduct = new BatchProduct()
{
Batch = batch
};
var existingProduct = db.Products.SingleOrDefault(p => p.ID == product.ID);
if (existingProduct != null)
{
batchproduct.Product = existingProduct;
}
else
{
batchproduct.Product = new Product()
{
};
}
db.BatchProducts.Add(batchproduct);
}
db.SaveChanges();
}