我们如何将EF Fluent API与反射类型一起使用

时间:2012-02-08 15:17:30

标签: entity-framework entity-framework-4 ef-code-first

如何使用流畅的API,几乎没有反复停止重复?

示例代码;

public abstract class Entity : IEntity
{
    public int Id { get; set; }
}

public class SemiStructuredEntity : Entity
{
    public virtual int DocumentId { get; set; }

    [ForeignKey("DocumentId")]
    public virtual Document Document { get; set; }
}

public class Payment : SemiStructuredEntity
{
    public string Code { get; set; }
}

public class Member : SemiStructuredEntity
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Document : Entity
{
    public string UniversalId { get; set; }
    public string Subject { get; set; }
}

且流利;

    modelBuilder.Entity<Member>()
        .HasRequired(a => a.Document)
        .WithMany()
        .HasForeignKey(u => u.DocumentId);

    modelBuilder.Entity<Payment>()
            .HasRequired(a => a.Document)
            .WithMany()
            .HasForeignKey(u => u.DocumentId);

当我们需要另一个由SemiStructuredEntity基类继承的类时,我们必须为它定义另一个流。

我的梦想是; (我的问题在代码块中注释了行)

    List<Type> targetTypes = getSemiStructuredEntities();
    ///
    ///and now  How? How can i define fluent for all of targetTypes in second statements?
    ///

List<Type> targetTypes = getSemiStructuredEntities();
foreach (Type item in targetTypes)
{
           ///
           ///And now How? How can i define fluent for this type
           ///
}

提前致谢。

1 个答案:

答案 0 :(得分:1)

为什么要使用反射?您可以使用EntityTypeConfiguration<>派生的类型定义地图in reusable way,并在modelBuilder.Configurations方法中将这些类型注册到OnModelCreation