我开始在 .net core 中使用 Entityframework 7 和 Onion Architecture !我阅读了 this 教程,我认为这是学习以下主题的最佳案例。但是本教程的一部分在我的脑海中提出了一个大问题。就像您在此链接页面上看到的一样;在数据层,我们有一些类是我们的模型!!public class User : BaseEntity{ public string UserName { get; set; } public string Email { get; set; } public string Password { get; set; } public virtual UserProfile UserProfile { get; set; }}public class UserProfile : BaseEntity{ public string FirstName { get; set; } public string LastName { get; set; } public string Address { get; set; } public virtual User User { get; set; }}和一些像这样映射模型的类!public class UserProfileMap{ public UserProfileMap(EntityTypeBuilder<UserProfile> entityBuilder) { entityBuilder.HasKey(t => t.Id); entityBuilder.Property(t => t.FirstName).IsRequired(); entityBuilder.Property(t => t.LastName).IsRequired(); entityBuilder.Property(t => t.Address); }}public class UserMap{ public UserMap(EntityTypeBuilder<User> entityBuilder) { entityBuilder.HasKey(t => t.Id); entityBuilder.Property(t => t.Email).IsRequired(); entityBuilder.Property(t => t.Password).IsRequired(); entityBuilder.Property(t => t.Email).IsRequired(); entityBuilder.HasOne(t => t.UserProfile).WithOne(u => u.User).HasForeignKey<UserProfile>(x => x.Id); }}它在 DbContext 的 OnModelCreating 方法中使用此映射器类在数据库中创建以下模型作为表:public class ApplicationContext : DbContext{ public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); new UserMap(modelBuilder.Entity<User>()); new UserProfileMap(modelBuilder.Entity<UserProfile>()); }}我的大问题是:我们可以为 db 上下文中的每个实体使用 DbSet<> 并避免编写映射器并在 OnModelCreating 的 dbcontext 方法中实例化它们。为什么本教程没有使用 dbset ?为什么我们必须创建映射器! 最佳答案 new UserMap(modelBuilder.Entity<User>()); 基本上是使用 Fluent API 配置和映射实体到 DbSet 的 EF Core 方式。 DbSet 对于db context 和 使用Mapper 配置DbSet 中的每个实体是相同的。在 Entity Framework 6 中,我们使用 EntityTypeConfiguration 并创建映射类,如 this 。与数据注释相比,它非常干净,并且遵循单一职责原则。美妙之处在于我们只需要 the following code 就可以使用反射自动配置数百个实体。protected override void OnModelCreating(DbModelBuilder modelBuilder){ ... var typesToRegister = Assembly.GetExecutingAssembly().GetTypes() .Where(type => !string.IsNullOrEmpty(type.Namespace) && type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof (EntityTypeConfiguration<>)); foreach (var type in typesToRegister) { dynamic configurationInstance = Activator.CreateInstance(type); modelBuilder.Configurations.Add(configurationInstance); } base.OnModelCreating(modelBuilder);}此外,我们可以使用 Entity Framework Power Tools ,并从现有数据库创建实体和映射配置。将数百个表生成到类中只需要大约几分钟的时间。这对我们来说节省了很多时间。不幸的是,截至今天,EntityTypeConfiguration<T> 在 EF Core 中尚不可用。我认为我们很多人仍然喜欢使用旧方法和新的 EntityTypeBuilder<T> 来将 Mapping 配置保留在 DbContext 之外,尽管它不像我们在 EF6 中所做的那样顺利。关于c# - 在 EF7 中使用 dbset 和映射器有什么区别,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45166219/
10-17 02:30