标签:where oid base ima weixin protected ase 核心 技术分享
先安装 Install-Package MySql.Data.EntityFrameworkCore
创建3个表
创建类
public class Role
{
public long Id { get; set; }
public string Name { get; set; }
}
public class User
{
public long Id { get; set; }
public string Name { get; set; }
}
public class UserRoleRelation
{
public long Id { get; set; }
public long UserId { get; set; }
public long RoleId { get; set; }
public User User { get; set; }
public Role Role { get; set; }
}
编写DbContext,ef core的DbContext等EF的核心类在using Microsoft.EntityFrameworkCore;
public class MyDbContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<UserRoleRelation> UserRoleRelations { get; set; }
public DbSet<weixin_userinfo> WeixinUserinfo { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseMySQL("Server=127.0.0.1;database=test;uid=root;pwd=123456");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
var typeUser = modelBuilder.Entity<User>();
typeUser.ToTable("T_Users");
var typeRole = modelBuilder.Entity<Role>();
typeRole.ToTable("T_Roles");
var typeUserRoleRelation = modelBuilder.Entity<UserRoleRelation>();
typeUserRoleRelation.ToTable("T_UserRoleRelations");
/**
* 多对多:不用中间实体的多对多还不支持,要自己拆成用中间实体的两对一对多。
* EF中(一对多)写法:builder.HasRequired(e => e.Role).WithMany();
*/
typeUserRoleRelation.HasOne(e=>e.Role).WithMany().HasForeignKey(e=>e.RoleId).IsRequired();
typeUserRoleRelation.HasOne(e=>e.User).WithMany().HasForeignKey(e=>e.UserId).IsRequired();
}
}
运行:
using (MyDbContext ctx = new MyDbContext())
{
var user = ctx.Users.First();
long userId = user.Id;
var relactions = ctx.UserRoleRelations.Include(e => e.Role)
.Where(r => r.UserId == userId);
foreach (var relation in relactions)
{
Console.WriteLine(relation.Role.Name);
}
}
链接:EF Fluent API https://www.cnblogs.com/tangge/p/9831957.html
标签:where oid base ima weixin protected ase 核心 技术分享
原文地址:https://www.cnblogs.com/tangge/p/10041692.html