博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
EF Core Fluent API
阅读量:6267 次
发布时间:2019-06-22

本文共 6032 字,大约阅读时间需要 20 分钟。

多对多配置

先安装 Install-Package MySql.Data.EntityFrameworkCore

创建3个表

196558-20181129232131533-846728480.png

创建类

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
Users { get; set; } public DbSet
Roles { get; set; } public DbSet
UserRoleRelations { get; set; } public DbSet
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
(); typeUser.ToTable("T_Users"); var typeRole = modelBuilder.Entity
(); typeRole.ToTable("T_Roles"); var typeUserRoleRelation = modelBuilder.Entity
(); 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(); } }

通过UseMySQL这样的扩展方法来配置连接字符串,这是.Net core的风格!可以把连接字符串写到配置文件中,然后再读取。

运行:

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

EntityTypeConfiguration

ef core 1.1

没有内置EntityTypeConfiguration,需要手动自己注册一个

  1. IEntityTypeConfiguration.cs
using Microsoft.EntityFrameworkCore;namespace Entity.Config{    public interface IEntityTypeConfiguration    {        void Map(ModelBuilder builder);    }    public interface IEntityTypeConfiguration
: IEntityTypeConfiguration where T : class { void Map(ModelBuilder builder); }}
  1. EntityTypeConfiguration.cs
using Microsoft.EntityFrameworkCore;using Microsoft.EntityFrameworkCore.Metadata.Builders;namespace Entity.Config{    public abstract class EntityTypeConfiguration
: IEntityTypeConfiguration
where T : class { public abstract void Map(EntityTypeBuilder
builder); public void Map(ModelBuilder builder) { Map(builder.Entity
()); } }}
  1. ModelBuilderExtenions.cs
using Microsoft.EntityFrameworkCore;namespace Entity.Config{    public static class ModelBuilderExtenions    {        private static IEnumerable
GetMappingTypes(this Assembly assembly, Type mappingInterface) { return assembly.GetTypes().Where(x => !x.GetTypeInfo().IsAbstract && x.GetInterfaces().Any(y => y.GetTypeInfo().IsGenericType && y.GetGenericTypeDefinition() == mappingInterface)); } public static void AddEntityConfigurationsFromAssembly(this ModelBuilder modelBuilder, Assembly assembly) { var mappingTypes = assembly.GetMappingTypes(typeof(IEntityTypeConfiguration<>)); foreach (var config in mappingTypes.Select(Activator.CreateInstance).Cast
()) { config.Map(modelBuilder); } } }}

修改MyDbContext.cs

protected override void OnModelCreating(ModelBuilder modelBuilder)        {            base.OnModelCreating(modelBuilder);            //modelBuilder.AddEntityConfigurationsFromAssembly(Assembly.GetEntryAssembly());//参数表示config类所在的程序集            modelBuilder.AddEntityConfigurationsFromAssembly(Assembly.Load("Entity"));//这里加载的是 Entity程序集            ...        }

下面示例创建一个UserRoleRelationConfig.cs,其他自己建

using Microsoft.EntityFrameworkCore;using Microsoft.EntityFrameworkCore.Metadata.Builders;namespace Entity.Config{    public class UserRoleRelationConfig:EntityTypeConfiguration
{ public override void Map(EntityTypeBuilder
builder) { builder.ToTable("T_UserRoleRelations"); /** * 多对多:不用中间实体的多对多还不支持,要自己拆成用中间实体的两对一对多。 * EF中(一对多)写法:builder.HasRequired(e => e.Role).WithMany(); */ builder.HasOne(e => e.Role).WithMany().HasForeignKey(e => e.RoleId).IsRequired(); builder.HasOne(e => e.User).WithMany().HasForeignKey(e => e.UserId).IsRequired(); } }}

ef core 2.0

EF Core 2.0 中内置了 IEntityTypeConfiguration

public class UserRoleRelationConfig:IEntityTypeConfiguration
{ public void Configure(EntityTypeBuilder
builder) { builder.ToTable("T_UserRoleRelations"); /** * 多对多:不用中间实体的多对多还不支持,要自己拆成用中间实体的两对一对多。 * EF中(一对多)写法:builder.HasRequired(e => e.Role).WithMany(); */ builder.HasOne(e => e.Role).WithMany().HasForeignKey(e => e.RoleId).IsRequired(); builder.HasOne(e => e.User).WithMany().HasForeignKey(e => e.UserId).IsRequired(); } }

转载地址:http://fidpa.baihongyu.com/

你可能感兴趣的文章
PYTHON1.day09
查看>>
复制、移动和删除:cp, rm, mv
查看>>
Return View()
查看>>
HDU 6156 回文 数位DP(2017CCPC)
查看>>
AndroidManifest.xml文件剖析
查看>>
沛齐的315面试题基础部分解答(一)
查看>>
bzoj2662 冻结
查看>>
(转)Odoo 是什么?
查看>>
浅谈当下7个网页设计趋势(转)
查看>>
2011年工作总结和展望(下篇)
查看>>
如何在VUE项目中使用SCSS
查看>>
开放源代码的设计层面框架Spring——day02
查看>>
[SP694][SP705]DISUBSTR - Distinct Substrings/SUBST1 - New Distinct Substrings[SA]
查看>>
JavaScript中的三种弹窗
查看>>
确认框,confirm工具封装
查看>>
常用css和js组件
查看>>
HDU-4528 小明系列故事——捉迷藏 BFS模拟
查看>>
〖Android〗/system/etc/event-log-tags
查看>>
深入浅出 JavaScript 变量、作用域和内存 v 0.5
查看>>
Jquery 选择器大全 【转载】
查看>>