我有以下流程:
我应该如何正确创建实体:stub(默认构造函数)或DbSet<T>.Create()
?
我应该如何正确保存实体:DbSet<T>.Add()
或DbSet<T>.Attach()
?
我遇到了各种例外:
“违反PRIMARY KEY约束'PK_currency_types'。无法在对象'dbo.currency_types'中插入重复键。重复键值为(1)。语句已终止。”
“发生了引用完整性约束违规:定义引用约束的属性值在关系中的主体和从属对象之间不一致。”
我正在使用EF 4.3 Database First(我有数据库,设计器,但实体是自动生成的POCO),带有DbContext Generator扩展。我是EF的新手,完全陷入困境。
更新:这是我的代码,很简单所以我从一开始就没有添加它:
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();
}
}
}
答案 0 :(得分:0)
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();