You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
72 lines
2.1 KiB
72 lines
2.1 KiB
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<User>();
|
|
modelBuilder.Entity<Role>();
|
|
modelBuilder.Entity<UserRole>().HasOne(o => o.User).WithMany(o => o.UserRoles).HasForeignKey(o => o.UserId);
|
|
modelBuilder.Entity<UserRole>().HasOne(o => o.Role).WithMany(o => o.UserRoles).HasForeignKey(o => o.RoleId);
|
|
modelBuilder.Entity<UserRole>().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<UserRole> UserRoles { get; set; } = new List<UserRole>();
|
|
}
|
|
|
|
public class Role : Entity
|
|
{
|
|
public string Name { get; set; }
|
|
public List<UserRole> UserRoles { get; set; } = new List<UserRole>();
|
|
}
|
|
|
|
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<User>().Add(new User { UserName = "test" });
|
|
db.SaveChanges();
|
|
}
|
|
Console.WriteLine(db.Set<User>().FirstOrDefault()?.UserName);
|
|
}
|
|
}
|
|
}
|
|
}
|