I am working with Entity Framework using the code-first approach. I have successfully seeded data for a many-to-many relationship (Type to Status). Now I need to seed data for a many-to-many relationship between Status and SubStatus.
I first create all the statuses, and then I add each Type and add the many-to-many relationship with each status.
Here is what I have for Type and 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"),
}
};
How can I build off of this to then add the many-to-many relationship between Status and SubStatus now?
Here's a list of a couple of SubStatuses:
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);
}
I believe you are looking for a parent / child relationship? You could restructure your Status
entity like this and remove the SubSatus
class:
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;}
}
Then you can append ChildStatuses
and associate them with a 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() );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.