Quantcast
Channel: ADO.NET, Entity Framework, LINQ to SQL, NHibernate
Viewing all articles
Browse latest Browse all 1698

How to manually define DBContext code snippet for table without primary keys?

$
0
0

Hello,

I followed these instructions ( https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db ) to automatically create database models/entity classes and the DBContext class, however one of the tables does not have any primary keys defined so the Scaffold-DbContext command did not generate the entity class for it. 

This table is basically a small 2 column table for defining a many-to-many relationship between 2 other tables.

Creating the Entity class was straight forward, but what should the proper code snippet be for the DBContext class for this?  

The manually created Entity class:

public class UserLocationManyToMany
{


    public int UserId { get; set; }

    public int? LocationId { get; set; }


}

The following is the DBContext code snippet (pls correct if incorrect):

modelBuilder.Entity<UserLocationManyToManyTable>(entity =>
{

entity.ToTable("UserLocation");
entity.HasIndex(e => e.UserId).HasName("userId_idx");

entity.Property(e => e.UserId).HasColumnName("userId");
entity.Property(e => e.LocationId).HasColumnName("locationId");

}

In addition to the statements above, does anyone know how to define the following?:

  1. the many-to-many relationship (between "User" table to "Location" table)
  2. the primary key (my understanding is that this is necessary)

Thanks!

victor


Viewing all articles
Browse latest Browse all 1698

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>