I have the follow flow:
How should I properly create an entity: stub (by default constructor) or DbSet<T>.Create()
?
How should I properly save the entity: DbSet<T>.Add()
or DbSet<T>.Attach()
?
I'm getting various exceptions:
"Violation of PRIMARY KEY constraint 'PK_currency_types'. Cannot insert duplicate key in object 'dbo.currency_types'. The duplicate key value is (1). The statement has been terminated."
"A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship."
I'm using EF 4.3 Database First (I have database, designer but entities are auto-generated POCOs) with DbContext Generator extension. I'm new to EF and completely stuck.
Update: Here's my code, it's simple so I haven't added it from the beginning:
public IStatement Create()
{
using (var db = new ModelContainer())
{
// ID is auto-generated by db, INT IDENTITY(1,1)
return new Statement();
// or
// return b.Statement.Create();
}
}
// somewhere in the middle, for example:
statement.Currency = db.Currency.Single(c => c.Name == "Euro");
statement.Amount = 1000;
public void Save(IStatement[] statement)
{
using (var scope = new TransactionScope())
using (var db = new ModelContainer())
{
foreach (var s in statement)
{
// statement has a number of navigation properties, i.e. referenced by FK entities
// need to add/attach each back to db
}
db.SaveChanges();
scope.Complete();
}
}
}
var statement = new Statement();
using (var scope = new TransactionScope())
{
var result = 0;
foreach (var statement in arr.Cast<Statement>())
{
using (var db = new ModelContainer())
{
db.StatementTypes.Attach(statement.StatementType);
db.Entry(statement.StatementType).State = EntityState.Unchanged;
db.Currencies.Add(statement.Currency);
db.Entry(statement.Currency).State = EntityState.Unchanged;
db.Subjects.Attach(statement.Firm);
db.Entry(statement.Firm).State = EntityState.Unchanged;
db.Statement.Add(statement);
db.SaveChanges();
}
}
scope.Complete();