Alexandre Brisebois
Alexandre Brisebois

Reputation: 6743

Examples of using F# to query Entity Framework

I'm looking all over Google to find an example or tutorial about using F# to query an Entity data source.

Honestly I haven't found much. Have any of you had any luck ?

Upvotes: 8

Views: 2443

Answers (2)

Rm558
Rm558

Reputation: 4992

Tons of examples in here

return a record type

type T1 = {F1: int32; F2: string}
let q = query {
  for t in ctx.SomeTable do 
  select { F1 = t.F1
           F2 = t.F2 } 
};

return anonymous type, {| ... |}, there is still some bug, the ugly workaround is appending a .ToList() to the table.

let q = query {
  for t in ctx.SomeTable.ToList() do 
  select 
        {| F1 = t.F1
           F2 = t.F2 
        |} 
};

Update a record in EF Core

let obj = ctx.SomeTable.Where(fun t->t.ID = 123).Single()
obj.FieldX <- "new Value"
ctx.SaveChanges() |> ignore

Upvotes: 1

Alexandre Brisebois
Alexandre Brisebois

Reputation: 6743

The following is an example I was able to pieces together from what i found on this blog

open Microsoft.FSharp.Linq.QuotationEvaluation
open Microsoft.FSharp.Linq

let IsPermited (serviceName:string) =
  //Instantiate the Entity 
  let data = new BusModelContainer()

  //Build your query
  let services = Query.query <@ seq{ for service in data.ServiceSet do
                         service.Name.Equals(serviceName) && service.IsEnabled then
                               yield service } @>
  if Seq.is_empty services then 
    false
  else
    true

Here is the code from the blog that showed me how to go about selecting from an Entity

  let db = new FSharpSampleDB(connString)  

  Query.query <@ seq { for c in db.Customers do  
                       if id = c.CustomerId then  
                          yield (new Customer(c.CustomerId, c.Name, c.Balance))}   
              |> Seq.hd @> :> ICustomer  

Upvotes: 6

Related Questions