public class Product
{
public int Id { get; set; }
public string Name{ get; set; }
// lotsa other stuff
public ICollection RelatedProduct{ get; set; }
}
Hi,
Let's say I have a table "Product"
That table has a collection of 'Related Products'
Ho do I configure it on the DbContext fulent api so it creates the link table?
One product can be in many "relatedproducts" and each product can have many "relatedproducts"
Prasad RaveendranPosted Jun 6, 2023, 2:55 AM
To create a many-to-many relationship on the same table in SQL using Entity Framework, you can follow these steps:
1. Define the model class for the table. Let's assume you have a table named "Person" with a primary key "Id" and a self-referencing foreign key "FriendId" that represents the many-to-many relationship.
2. Configure the many-to-many relationship in your DbContext class by overriding the OnModelCreating method. Use the Fluent API to define the relationship.
3. Use the Friends and FriendOf properties to navigate the many-to-many relationship.
In this example, we create a many-to-many relationship between people using the Friends and FriendOf properties. We define the relationship in the OnModelCreating method using the HasMany and WithMany methods. The UsingEntity method is used to configure the intermediate table, "Friendship," that stores the relationship data. Finally, we can create and save entities to establish the many-to-many relationship.
Mudzakkir TohaPosted Jun 5, 2023, 11:38 PM
You can create tables first. and do scaffold to your project
try to search scaffold on youtube or you can learn here
https://www.entityframeworktutorial.net/efcore/create-model-for-existing-database-in-ef-core.aspx
Andre SilveiraPosted Jun 5, 2023, 11:14 PM
@Mudzakkir Toha
But how do I do it in EF core? I know how to make it in SQL server, but I need it in entity framework core..
Mudzakkir TohaPosted Jun 5, 2023, 10:49 PM
There are number ways to achieve this.
In Example you create product tags, which is relation table between product and tag tables.