Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework CTP5 (Code First) Modeling - lookup tables

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?

like image 860
Chris Klepeis Avatar asked Feb 22 '11 16:02

Chris Klepeis


People also ask

What is a lookup table in Entity Framework?

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.

What approach do you use to create tables in Entity Framework?

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.

How to create an Entity Framework data model in Visual Studio?

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

How do I create an ADO 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


1 Answers

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"); 

});
like image 61
mxmissile Avatar answered Oct 06 '22 05:10

mxmissile