从F#调用EF Core HasIndex

时间:2018-03-31 14:23:10

标签: f# ef-code-first entity-framework-core

我试图将一个C#EF Core示例(类似于the one in the docs)重写为F#。我对HasIndex有疑问。在C#中,调用是HasIndex(b => b.Isbn),以在Isbn列上创建索引:

public class SampleContext : DbContext
{
    public DbSet<Book> Books { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Book>().HasIndex(b => b.Isbn);
    }
}

在F#中执行相同操作HasIndex(fun b -> b.Isbn),不编译:

type public SampleContext() =
    inherit DbContext()

    [<DefaultValue>]
    val mutable books: DbSet<Book>

    member x.Books
        with get() = x.books
        and set v = x.books <- v

    override __.OnModelCreating(modelBuilder) =
        modelBuilder.Entity<Book>().HasIndex(fun b -> b.Isbn) // doesn't compile
        |> ignore

我是否需要使用引用魔法才能使其正常工作?

(你当然可以使用字符串HasIndex("Isbn"),但我不想把编译时检查抛到窗外。)

1 个答案:

答案 0 :(得分:2)

根据https://social.msdn.microsoft.com/Forums/vstudio/en-US/a0757965-4d13-4f88-910f-9ab5fd96277d/how-to-convert-c-linq-expression-in-f?forum=fsharpgeneral中接受的答案:

&#34;当您传递一个预期表达式的lambda时,F#3.0或更高版本应该应用类型导向的转换。&#34;

似乎F#3.0及更高版本将转换lambda,只要用括号括起它并将返回值强制转换为C#方法所期望的特定类型(在本例中为&#34; Sytem.Object&#34 ;)

所以:

modelBuilder.Entity<Book>().HasIndex( (fun b -> b.Isbn :> System.Object ) )

在.net core 2.0中成功编译