using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; namespace EFCoreTest { public class MyDbContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlite("Data Source=data.db;"); //optionsBuilder.UseMySql("Server=139.180.143.95;Port=3306;Database=test;Uid=admin;Pwd=admin;"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity(); modelBuilder.Entity(); modelBuilder.Entity().HasOne(o => o.User).WithMany(o => o.UserRoles).HasForeignKey(o => o.UserId); modelBuilder.Entity().HasOne(o => o.Role).WithMany(o => o.UserRoles).HasForeignKey(o => o.RoleId); modelBuilder.Entity().HasIndex(o => new { o.UserId, o.RoleId }).IsUnique(); } } public class Entity { public Guid Id { get; set; } public Entity() { this.Id = Guid.NewGuid(); } } public class User : Entity { public string UserName { get; set; } public List UserRoles { get; set; } = new List(); } public class Role : Entity { public string Name { get; set; } public List UserRoles { get; set; } = new List(); } public class UserRole : Entity { public Guid UserId { get; set; } public Guid RoleId { get; set; } public User User { get; set; } public Role Role { get; set; } } class Program { static void Main(string[] args) { using (var db = new MyDbContext()) { if (db.Database.EnsureCreated()) { db.Set().Add(new User { UserName = "test" }); db.SaveChanges(); } Console.WriteLine(db.Set().FirstOrDefault()?.UserName); } } } }