我正在使用代码优先方法使用Entity Framework。我已经成功地为多对多关系(类型到状态)播种数据。现在我需要为Status和SubStatus之间的多对多关系建立数据。
我首先创建所有状态,然后添加每个类型并添加每个状态的多对多关系。
以下是我的类型和状态:
var text = $('.question_description').contents().first().text();
console.log(text) // return question to test autolinker
我如何构建它,然后立即添加Status和SubStatus之间的多对多关系?
这里列出了几个SubStatuses:
IList<Status> statuses = new List<Status>();
statuses .Add(new Status() { Value = "On" });
statuses .Add(new Status() { Value = "Off" });
foreach (Status s in statuses)
{
context.Set<Status>().AddOrUpdate(s);
}
Type type1 = new Type()
{
Value = "Type 1",
Status = new List<Status>()
{
statuses.FirstOrDefault(e => e.Value == "On"),
statuses.FirstOrDefault(e => e.Value == "Off")
}
};
Type type2 = new Type()
{
Value = "Type 2",
Status = new List<Status>()
{
statuses.FirstOrDefault(e => e.Value == "On"),
}
};
答案 0 :(得分:0)
我相信您正在寻找父母/子女的关系?您可以像这样重新构建Status
实体并删除SubSatus
类:
public class Type
{
public string Value {get;set;}
public ICollection<Status> Statuses {get;set;}
{
public class Status
{
public string Value {get;set;}
public int? ParentStatusId {get;set;}
public Status ParentStatus {get;set;}
public ICollection<Status> ChildStatuses {get;set;}
Public ICollection<Type> Types {get;set;}
}
然后,您可以附加ChildStatuses
并将其与ParentStatus
var typeA = new Type()
{
Value = "Type A"
};
var typeB = new Type()
{
Value = "Type B"
};
var statuses = new List<Status>(){
new Status()
{
Value = "On",
ChildStatuses = new List<Status>(){
new Status()
{
Value = "Success",
Types = new List<Type>()
{
typeA,
typeB
}
},
new Status()
{
Value = "Fail",
Types = new List<Type>()
{
typeB
}
}
}
};
context.Set<Status>().AddOrUpdate(s => s.Value, statuses.ToArray() );