In the article, we will connect (One to Many) and (Many to Many) use Fluent API in EF Core, you can see: https://www.entityframeworktutorial.net/efcore/entity-framework-core.aspx
The First, go to create project ASP.NET Core 2.1->Select model MVC, continue you need install Entityframework Core in Project
Ok open Nutget->install 3 plugin after
Microsoft.EntityFrameworkCore Microsoft.EntityFrameworkCore.SqlServer Microsoft.EntityFrameworkCore.Tools
If you set up plugin complete, now need modify ConnectionStrings in appsetting.json file
{ "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*", "ConnectionStrings": { "EFDataContext": "Server=DESKTOP-GCABV8F\\SQLExpress;Database=DBcore;Trusted_Connection=True;MultipleActiveResultSets=true" } }
Okay, now we set up model data and set up properties in model class
- User -> HasMany(Role) => CREATE class Models/User.cs [idUser,Name,Age] - Role -> HasMany(User) => CREATE class Models/Role.cs [idRole,Name] - UserRole -> WithOne(Role,User) => CREATE class Models/UserRole.cs [idRole,idUser] - User -> HasMany(Post) - Post -> WithOne(User) => CREATE class Models/Post.cs [idPost,Title,Body,idUser]
- Models/User.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace RelationshipCoreFirst_ASPcore.Models { public class User { public int idUser { get; set; } public string Name { get; set; } public int Age { get; set; } public virtual ICollection<UserRole> UserRoles { get; set; } public virtual ICollection<Post> Posts { get; set; } } }
- Models/Role.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace RelationshipCoreFirst_ASPcore.Models { public class Role { public int idRole { get; set; } public string Name { get; set; } public virtual ICollection<UserRole> UserRoles { get; set; } } }
- Models/UserRole.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace RelationshipCoreFirst_ASPcore.Models { public class UserRole { public int idUser { get; set; } public int idRole { get; set; } public User User { get; set; } public Role Role { get; set; } } }
- Models/Post.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace RelationshipCoreFirst_ASPcore.Models { public class Post { public int idPost { get; set; } public string Title { get; set; } public string Body { get; set; } public int idUser { get; set; } public User User { get; set; } } }
After when set up model class in Models folder, we need set up DBContext, DBContext important in Entityframework core, support set up Data in SQL SERVER
- Models/EFDataContext.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace RelationshipCoreFirst_ASPcore.Models { public class EFDataContext : DbContext { public EFDataContext(DbContextOptions<EFDataContext> options) : base(options){} protected override void OnModelCreating(ModelBuilder modelBuilder) { //config primary key(Role, User,Post,UserRole) modelBuilder.Entity<Post>().HasKey(s => s.idPost); modelBuilder.Entity<User>().HasKey(s => s.idUser); modelBuilder.Entity<Role>().HasKey(s => s.idRole); modelBuilder.Entity<UserRole>().HasKey(s => new { s.idUser, s.idRole }); //configuration relationship table(User & Post) modelBuilder.Entity<Post>() .HasOne(s => s.User) .WithMany(s => s.Posts) .HasForeignKey(s => s.idUser) .OnDelete(DeleteBehavior.Restrict); // Relationships table User,Role,UserRole modelBuilder.Entity<UserRole>() .HasOne<User>(sc => sc.User) .WithMany(s => s.UserRoles) .HasForeignKey(sc => sc.idUser); modelBuilder.Entity<UserRole>() .HasOne<Role>(sc => sc.Role) .WithMany(s => s.UserRoles) .HasForeignKey(sc => sc.idRole); } public DbSet<User> Users { get; set; } public DbSet<Role> Roles { get; set; } public DbSet<UserRole> UserRoles { get; set; } public DbSet<Post> Posts { get; set; } } }
In the code above, we set up primary table and set relationship table
Now, we need register EFDataContext.cs to Startup.cs file. you add the following code below to ConfigureServices method
services.AddDbContext<EFDataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("EFDataContext")));
Continue, insert two line, the following below code to Startup.cs file
using Microsoft.EntityFrameworkCore; using RelationshipCoreFirst_ASPcore.Models;
- Startup.cs(FullCode)
using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.EntityFrameworkCore; using RelationshipCoreFirst_ASPcore.Models; namespace RelationshipCoreFirst_ASPcore { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddDbContext<EFDataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("EFDataContext"))); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
Okay, now we can run migration, open tab Tools->Nutget Packager Manager->Package Manager Console
add-migration dbcore_v1 update-database
Githup : https://github.com/skipperhoa/database-relationship-aspnet-core21
The Article : Database Relationships(One to Many, Many to Many) in ASP.NET CORE 2.1
Top comments (0)