How to work with many-to-many connections?
I implemented a program to work with the database, I used the Entity Framework , i.e. created model classes, etc.
When developing software, it turned out that two tables from the database should have a connection to many to many. When the base was created (the Codé First approach) another one appeared in the base between the two tables. In principle, everything works well, but due to the fact that this table appeared, I cannot work with it programmatically. I did not create a class (model) of this table as a result when I have some kind of Id
first table for which I need to get something from the second through LINQ I cannot do this, I have to write a query "manually". How can this problem be solved, so that it would be possible to work with many-to-many links programmatically via LINQ ?
ServiceStationContext db = new ServiceStationContext(); public class WorkOrder1 { public int Id { get; set; } public string Accepter { get; set; } public string Foreman { get; set; } public string myDate { get; set; } public ICollection<GuideWorkTypeStandardHour1> GuideWorkTypeStandardHour1s { get; set; } public WorkOrder1() { GuideWorkTypeStandardHour1s = new List<GuideWorkTypeStandardHour1>(); } } public class GuideWorkTypeStandardHour1 { public int Id { get; set; } public string CodeWork { get; set; } public ICollection<WorkOrder1> WorkOrder1s { get; set; } public GuideWorkTypeStandardHour1() { WorkOrder1s = new List<WorkOrder1>(); } }
Saving to DB:
private void button1_Click_1(object sender, EventArgs e) { WorkOrder1 wo = new WorkOrder1(); wo.myDate = maskedTextBoxData.Text; wo.Accepter = textBoxAccepter.Text; wo.Foreman = textBoxForeman.Text; wo.BestPractice = textBox4Recommendation.Text; db.WorkOrders.Add(wo); db.SaveChanges(); }
Reading from the database, taking into account the prompts specified below (ie, the property is now virtual
)
List<GuideWorkTypeStandardHour1> guideWorkTypeStandardHour1; WorkOrder1 workOrder1 = db.WorkOrders.Find(ListWorkOrders.workorderselectedId); var works = db.GuideWorkTypeStandardHour1s; foreach(var w in works) { if(workOrder1.GuideWorkTypeStandardHour1s.Contains(w)) { guideWorkTypeStandardHour1.Add(w); } }