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

时间:2016-11-20 18:54:30

标签: c# entity-framework asp.net-core entity-framework-core ef-fluent-api

我使用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");
                });


        }

我在EntityFrameworkCore中遇到的问题是

  1. 它在CustomerConfiguration()
  2. 中识别ToTable和Property关键字
  3. 它在OnModelCreating方法中识别出Configurations,HasRequired,MapLeftKey,MapRightKey,ToTable关键字
  4. 有人可以告诉我如何使用EntityFrameWork Core中的Fluent API实现这一目标

2 个答案:

答案 0 :(得分:5)

EF核心使用完全不同的API。因此,您必须先学习它。

作为示例:这是设置ToTable()的方式。

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .ToTable("blogs");
    }

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

Table Mapping

Relationships

Creating a Model

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

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>());
        }
    }
}

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

答案 1 :(得分:0)

指向table maping文档的直接链接。 阅读其余部分。 EF核心是一种新产品,而非升级到EF6。