种子代码首先是多对多,然后是多对多
本文关键字:然后 代码 种子 | 更新日期: 2023-09-27 18:05:58
我正在使用代码优先的方法与实体框架合作。我已经成功地为多对多关系(Type to Status)播种了数据。现在我需要为Status和SubStatus之间的多对多关系播种数据。
我首先创建所有状态,然后添加每个Type,并为每个状态添加多对多关系。
Type和Status的设置如下:
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"),
}
};
我如何在此基础上构建,然后在Status和SubStatus之间添加多对多关系?
下面是几个substatus的列表:
IList<SubStatus> subStatuses = new List<SubStatus>();
subStatuses.Add(new SubStatus() { Value = "Success" });
subStatuses.Add(new SubStatus() { Value = "Fail" });
foreach (SubStatus s in subStatuses)
{
context.Set<SubStatus>().AddOrUpdate(s);
}
我相信你正在寻找一个父母/孩子的关系?您可以像这样重组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() );