码迷,mamicode.com
首页 > Windows程序 > 详细

EF Core Fluent API

时间:2018-11-30 00:38:24      阅读:430      评论:0      收藏:0      [点我收藏+]

标签: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

EF Core Fluent API

标签:where   oid   base   ima   weixin   protected   ase   核心   技术分享   

原文地址:https://www.cnblogs.com/tangge/p/10041692.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!