实体框架6中的流畅Api不兼容实体框架核心

Tom*_*Tom 2 c# entity-framework entity-framework-core ef-fluent-api asp.net-core

我使用Entity Framework 6实现了Fluent API.使用EnityFrameworkCore实现相同时遇到问题.

下面是使用EntityFramework 6的Fluent API的代码

 public class CustomerConfiguration : EntityTypeConfiguration<Customers>
    {
        public CustomerConfiguration()
        {
            ToTable("Customers");
            Property(c => c.FirstName).IsRequired().HasMaxLength(50);
            Property(c => c.LastName).IsRequired().HasMaxLength(50);
            Property(c => c.Gender).IsRequired().HasMaxLength(10);
            Property(c => c.Email).IsRequired().HasMaxLength(25);
            Property(c => c.Address).IsRequired().HasMaxLength(50);
            Property(c => c.City).IsRequired().HasMaxLength(25);
            Property(c => c.State).IsOptional().HasMaxLength(15);

        }
    }


  protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new CustomerConfiguration());
            modelBuilder.Configurations.Add(new OrderConfiguration());
            modelBuilder.Configurations.Add(new ProductConfiguration());

            modelBuilder.Entity<Orders>()
           .HasRequired(c => c.Customers)
           .WithMany(o => o.Orders)
           .HasForeignKey(f => f.CustomerId);

            modelBuilder.Entity<Orders>()
                .HasMany<Products>(s => s.Products)
                .WithMany(c => c.Orders)
                .Map(cs =>
                {
                    cs.MapLeftKey("OrderRefId");
                    cs.MapRightKey("ProductRefId");
                    cs.ToTable("OrderDetails");
                });


        }
Run Code Online (Sandbox Code Playgroud)

我在EntityFrameworkCore中遇到的问题是

  1. 它可以识别CustomerConfiguration()中的ToTable和Property关键字
  2. 它在OnModelCreating方法中识别出Configurations,HasRequired,MapLeftKey,MapRightKey,ToTable关键字

有人可以告诉我如何使用EntityFrameWork Core中的Fluent API实现此目的

Sam*_*ath 5

EF核心使用完全不同的API.所以你必须先学习它.

举个例子:这就是它如何设置的方式ToTable().

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .ToTable("blogs");
    }
Run Code Online (Sandbox Code Playgroud)

要了解您必须阅读以下链接:

表映射

关系

创建模型

要在类中封装实体类型的配置:

using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace Microsoft.EntityFrameworkCore
{
    public abstract class EntityTypeConfiguration<TEntity>
        where TEntity : class
    {
        public abstract void Map(EntityTypeBuilder<TEntity> builder);
    }

    public static class ModelBuilderExtensions
    {
        public static void AddConfiguration<TEntity>(this ModelBuilder modelBuilder, EntityTypeConfiguration<TEntity> configuration)
            where TEntity : class
        {
            configuration.Map(modelBuilder.Entity<TEntity>());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在此处查看更多详细信息(请参阅由@rowanmiller编辑的第一篇文章:Github