net-core(EF Core)-使用表达式树还是委托
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; public class MemberConfig : IEntityTypeConfiguration<Member> { public void Configure(EntityTypeBuilder<Member> builder) { builder.ToTable("T_Member").HasKey(k => k.Id); builder.Property(c => c.Address).HasMaxLength(255); builder.Property(c => c.E_mail).HasMaxLength(100); } }
public class Member{ public int Id{get;set;} public string E_mail{get;set;} public string Name{get;set;} public string Address{get;set;} }
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Console; public class MyDbContext : DbContext { public DbSet<Member> members { get; set; } // public static readonly ILoggerFactory consoleLoggerFactory = LoggerFactory.Create(config=>config.AddConsole()); protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); var serverVersion = new MySqlServerVersion(new Version(8, 0, 27)); optionsBuilder .UseMySql( "Server=127.0.0.1;port=3306;Database=YBDDataBase;uid=root;pwd=ybdai930728;Character Set=utf8;" , serverVersion) //.UseLoggerFactory(consoleLoggerFactory); .LogTo(Console.WriteLine, LogLevel.Information) .EnableSensitiveDataLogging() .EnableDetailedErrors(); } // 这个是不能少的。 protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly); } }
如果是web项目
builder.Services.AddDbContext<MemberDbContext>();
关于使用表达式和委托的区别:
Expression<Func<Member,bool>> a1 = (c) => c.Address.Contains("q"); Func<Member,bool> f1 = (c) => c.Address.Contains("q"); using var db = new MyDbContext(); var s = db.members.Where(a1); var s2 = db.members.Where(f1); System.Console.WriteLine("hello world!");
两者生成的sql如下:
Expression: SELECT `t`.`Id`, `t`.`Address`, `t`.`E_mail`, `t`.`Name` FROM `T_Member` AS `t` WHERE `t`.`Address` LIKE '%q%' Func: SELECT `t`.`Id`, `t`.`Address`, `t`.`E_mail`, `t`.`Name` FROM `T_Member` AS `t`