私はエンティティフレームワークコードを最初に使用してSQLデータベースを設計し、 "SEED"メソッドを使用してデータベースに初期データを設定します。以下に、1対多数の関係を持つ2つのモデルを示します。 "フー" は、多くの "FooSection"エンティティフレームワークコンポジットキーが重複データを許可しない
public class Foo {
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int FooId {get; set;}
// Some more properties.
// Navigation collection
public virtual ICollection<FooSection> fooSections {get; set;}
}
public class FooSection {
// Has composite key
[ForeignKey("foo"), Column(Order=1)]
public int FooId {get; set;}
[Key, Column(Order=2)]
public string SectionName {get; set;}
// Some more properties
// Navigation property
public virtual Foo foo {get; set;}
}
がFooId = 1 "はFoo" の最初のインスタンスは、2 "FooSection" とFooId = 2で "foo" というの2つ目のインスタンスを持っていると言う、1 "FooSection" を有し有することができます。だから私のシード方法は次のようになります -
protected override void Seed(PDI.Cloud.Models.ApplicationDbContext context)
{
// First add data for "Foo"
var FooList = new List<Foo>();
if(!(context.Foos.Any()))
{
// First instance of Foo
FooList.Add(
new Foo{
// Assign values to properties here
}
);
// Second instance of Foo
FooList.Add(
new Foo{
// Assign values to properties here
}
);
FooList.ForEach(f => context.Foos.AddOrUpdate(f));
context.SaveChanges();
// Get info of "FooSection"
var fooSectList = getFooSectList(context);
// Assign "FooSection"s to respective "Foo".
FooList[0].fooSections.Add(fooSectList[0]); // Section 1 for Foo with id = 1
FooList[0].fooSections.Add(fooSectList[1]); // Section 2 for Foo with id = 1
FooList[1].fooSections.Add(fooSectList[2]); // Section 1 for Foo with id = 2
Context.SaveChanges();
}
}
private List<FooSection>getFooSectList(PDI.Cloud.Models.ApplicationDbContext context)
{
var FooSectList = new List<FooSection>();
if(!(context.FooSections.Any()))
{
// 1st FooSection for Foo with FooId = 1
FooSectList.Add(
new FooSection{
FooId = 1,
SectionName = "Sect1"
}
);
// 2nd FooSection for Foo with FooId = 1
FooSectList.Add(
new FooSection{
FooId = 1,
SectionName = "Sect2"
}
);
// 1st FooSection for Foo with FooId = 2
FooSectList.Add(
new FooSection{
FooId = 2,
SectionName = "Sect1"
}
);
FooSectList.ForEach(f => context.FooSections.AddOrUpdate(f));
context.SaveChanges();
}
return FooSectList;
}
私はシードメソッドを実行しようと、それはPRIMARY KEY制約の私のSQLException」違反を与えるオブジェクト内の重複するキーを挿入できません重複するキー値は(0、。。 Sect1) "
私はここに何か不足していますか?コンビネーションキーがユニークである限り私はコンポジットキーを考えるので、このようなエラーは発生しません。
私は助けていただきありがとうございます。
ありがとうございました。
ああ!キー"。はい、私はそれを逃していました。ありがとうsstan。 – Akshada