Assume the following table structure:
Tables:
**Tasks**
taskID int PK
taskName varchar
**Resources**
resourceID int PK
resourceName varchar
**Assignments**
assignmentID int PK
taskID int FK
resourceID int FK
The assignments table relates a task with the resource that is assigned to it. Is it possible to map this structure with the model builder so that I do not have to create an Assignment poco class - hiding some of the underlying data structure?
I.E.:
public class Task
{
public int taskID { get; set; }
public string taskName { get; set; }
public virtual ICollection<Resource> resourceItems { get; set; }
}
public class Resource
{
public int resourceID { get; set; }
public string resourceName { get; set; }
}
How can I use the model builder to map tasks to resources without creating an assignment poco class?
A lookup table in your Entity Framework Core database can be a more robust alternative to a simple enum when working with code-first C# data models. In this tutorial, you will learn how to create a lookup table and use its contents to populate a dropdown list in a Blazor application.
We designed and created tables with Code First approach in .Net Core with Entity Framework Core. You can access codes of project here. Hope to see you in the next post, I wish you healthy days.
We will use the Entity Framework Tools for Visual Studio to help us generate some initial code to map to the database. These tools are just generating code that you could also type by hand if you prefer. Project -> Add New Item… Select Data from the left menu and then ADO.NET Entity Data Model
These tools are just generating code that you could also type by hand if you prefer. Project -> Add New Item… Select Data from the left menu and then ADO.NET Entity Data Model Select the connection to the database you created in the first section and click Next Click the checkbox next to Tables to import all tables and click Finish
Here is an article about this very thing.
Edit, I dont have an IDE in front of me so this might not be the exact "latest" syntax, but it should get you started:
modelBuilder.Entity<Task>().HasMany(a => a.Resources).WithMany(b => b.Tasks).Map(m =>
{
m.MapLeftKey(a => a.TaskId,"taskId");
m.MapRightKey(b => b.ResourceId, "resourceId");
m.ToTable("Assignments");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With