I am using Entity Framework 3.5. My model has a Mediator table and a MediatorAvailabilities table. Most Mediators do not have an entry in MediatorAvailabilities (Availability = Null) but I still need to bring back the mediator whether or not there is a related MediatorAvailabilities.
My query below is only bring back a mediator if there is a related Availability. Again how do I get mediators even if Availability = null?:
Dim mediators = (From m In entity.Mediators.Include("MediatorAvailabilities") _
Where(m.MediatorAvailabilities.Any(Function(a) a.Availability = String.Empty Or a.Availability.Contains("Weekends") = True))
Where (m.isActive = True) _
Order By m.Sequence _
Select New RankingCriteria() With { _
.FirstName = m.FirstName, _
.LastName = m.LastName, _
.CompanyName = m.CompanyName, _
.PhoneHome = m.PhoneHome, _
.PhoneWork = m.PhoneWork, _
.PhoneMobile = m.PhoneMobile, _
.Email = m.Email _
}).ToList()
What's the correct way to do this?
I think you need to add a.Availability is Nothing in your Any method call like so:
Where(m.MediatorAvailabilities.Any(Function(a) a.Availability is Nothing Or a.Availability = String.Empty Or a.Availability.Contains("Weekends") = True))
Related
i have to queries which I want to merge.
these are two sample columns i want to compare.
i need to find the string from the second list, in the first one. If there is a match, append a list with the matching string to the first list.
Those lists are from two different queries
Those lists are from two different queries
That's fine, you can reference another query using its name. That could be Source1 and Source2 below.
need to find the string from the second list, in the first on
append a list with the matching string to the first list.
I wasn't sure if you meant
forall B in A =>
Text.Combine( {_} & {A}, "_")
I thought you meant to accumulate a list, that's what I did.
let
json1 = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45Wysw1NjIxNTMz0isoKlGK1QGJmJqhiiQnlsRD1SGpAvLj0TSiG1Wc9mH+hI1pWUBxHCowLcNqEUF7oBJA67YZG5sCqQ7jrDSIfCwA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [File = _t]),
Source1 = Table.TransformColumnTypes(json1,{{"File", type text}}),
json2 = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WSkzLyjEyNskyVYrViVYyNjKBMMzMjMD0h/kTtsEYHWBGZi6YgqlTio0FAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Substring = _t]),
Source2 = Table.TransformColumnTypes(json2,{{"Substring", type text}}),
/*
find all matching values in the source text
then merge the matching values with separator
optional params with defaults:
separator: string to join on, "_" by default
comparer: case sensitivity, off by default
*/
SummarizeMatchingText = (source as text, patterns as list, optional options as nullable record) as any =>
let
separator = options[separator]? ?? "_",
comparer = options[comparer]? ?? Comparer.OrdinalIgnoreCase,
select_matching = List.Select(
patterns,
(item) =>
Text.Contains( source, item, comparer)
),
merged = Text.Combine( select_matching, separator)
in
merged,
col_matches = Table.AddColumn(
Source1,
"Matches",
(row) =>
SummarizeMatchingText(
row[File], Source2[Substring],
[ separator = "—" ]
),
Text.Type
),
// summarize multiple steps
Summary = [
Source1 = Source1,
Source2 = Source2,
col_matches = col_matches,
expectEmpty = SummarizeMatchingText(
"sf🐱fj324", Source2[Substring] ),
expectMatch = SummarizeMatchingText(
"cat_im32456.prt", Source2[Substring] )
],
col_matches1 = Summary[col_matches]
in
col_matches1
I am trying to create a type safe data access layer in F# using FSharp.Data.SqlClient type providers to be callable from C#. I have highly complicated SQL queries that are performance critical but there are also several variations.
Given the following (obviously simplified schema):
CREATE TABLE [dbo].[company] (
[id] INT IDENTITY (1, 1) NOT NULL,
[name] VARCHAR (50) NOT NULL)
I have the following F# code:
module CompanyDAL =
open FSharp.Data // requires FSharp.Data.SqlClient package
[<Literal>]
let conn = "Data Source=(localdb)\ProjectsV13;Initial Catalog=TESTDB;Integrated Security=True;Pooling=False;Connect Timeout=30"
[<Literal>]
let baseQuery = "select id, name from company where 1 = 1 "
[<Literal>]
let filterById = "and id = #id"
[<Literal>]
let filterByName = "and name = #name"
[<Literal>]
let queryFilteredById = baseQuery + filterById
type GetCompanyById = SqlCommandProvider<queryFilteredById, conn>
[<Literal>]
let queryFilterbyName = baseQuery + filterByName
type GetCompanyByName = SqlCommandProvider<queryFilterbyName, conn>
type GetAllCompanies = SqlCommandProvider<baseQuery, conn>
type Company = {
Name : string
id : int
}
let getCompanyById (runtimeConn:string) =
async {
use query = new GetCompanyById(runtimeConn)
let! result = query.AsyncExecute(id = 10)
return result
|> Seq.map (fun x ->
{ Name = x.name
id = x.id })
|> Seq.toArray
} |> Async.StartAsTask
let getCompanyByName (runtimeConn:string) =
async {
use query = new GetCompanyByName(runtimeConn)
let! result = query.AsyncExecute(name = "abc" )
return result
|> Seq.map (fun x ->
{ Name = x.name
id = x.id })
|> Seq.toArray
} |> Async.StartAsTask
let getAllCompanies (runtimeConn:string) =
async {
use query = new GetAllCompanies(runtimeConn)
let! result = query.AsyncExecute()
return result
|> Seq.map (fun x ->
{ Name = x.name
id = x.id })
|> Seq.toArray
} |> Async.StartAsTask
Is there any way I can reduce the number of duplication while maintaining the raw performance of type safe raw queries?
I've tried using
type GetCompany = SqlEnumProvider<baseQuery, conn, provider>
Then I can write this code
GetCompany.Items |> Seq.where(fun (id, name) -> name = "xxx") |> printfn "%A"
So I can avoid duplication and pass a generic predicate fun (id, name) -> to the only GetCompany type.
Similarly,
GetCompany.Items |> Seq.where(fun (id, name) -> id = "1")
would work as well.
Note
Anyway, notice that the above will filter in memory. In fact Dynamic SQL is not permitted with this library, because it relies only on static analysis at compile time. If you need to construct queries dynamically, you can revert to raw ADO.NET or other light ORM.
New to scala and scalafx and having an issue with a tableview in a simple stock quote app [note: no prior javafx experience except in ways it is similar to things Android]
Problem: (see image) erroneous data displayed in change column where there should be none.
To create: Multiple scenarios, shown here is entry of new ticker symbol. It seems unpredictable how many cells are in error. Changing window size (say shorter then taller) generally creates more bad cells. Never happens if no change to windowsize and/or symbol list are made.
Code for the 'ticker' and 'change' columns below, though I suspect it is something in how I implemented the change column to do green/red text coloring.
(Note: data is updated in a single batch periodically which is why the new symbol does not immediately display quote data)
val colTicker = new TableColumn[Quote, String] {
editable = true
text = "Ticker"
prefWidth = 80
alignmentInParent = scalafx.geometry.Pos.Center
cellValueFactory = {
_.value.ticker
}
cellFactory = _ => new TextFieldTableCell[Quote, String](new DefaultStringConverter())
onEditCommit = (evt: CellEditEvent[Quote, String]) => {
val quote: Quote = evt.rowValue
val newTickerVal: String = evt.newValue.toUpperCase()
val oldTickerVal: String = evt.oldValue
// is it a valid ticker and not a dupe or is it blank (erase old ticker)?
if ((isValidTicker(newTickerVal) || newTickerVal.length == 0) && !symbolList.contains(newTickerVal)) {
// lock in the new value on the screen
quote.ticker.set(newTickerVal)
// if the new value is not empty add it to symbol list
if (newTickerVal.length > 0) {
symbolList.append(newTickerVal)
}
// now delete the old value
symbolList -= oldTickerVal
// sort and add another blank line
characters.sortWith(_.ticker.getValueSafe < _.ticker.getValueSafe)
if (oldTickerVal.length < 1) characters += Quote()
// now need to update the data file
putListToFile(dataFile, symbolList.sorted)
} else {
// bad ticker so keep the old one and don't update file
quote.ticker.set(oldTickerVal)
evt.getTableView.getColumns.get(0).setVisible(false)
evt.getTableView.getColumns.get(0).setVisible(true)
println("bad ticker, exiting symbol list: " + symbolList)
}
}
}
val colLast = new TableColumn[Quote, String] {
editable = false
text = "Last"
cellValueFactory = {
_.value.last
}
prefWidth = 80
alignmentInParent = scalafx.geometry.Pos.Center
}
val colChange = new TableColumn[Quote, String] {
editable = false
text = "Change"
cellFactory = {
_ =>
new TableCell[Quote, String] {
item.onChange { (_, _, newChange) =>
if (newChange != null) {
if (newChange.toString.contains("+")) textFill = Color.Green
else textFill = Color.Red
text = newChange
}
}
}
}
cellValueFactory = {
_.value.change
}
prefWidth = 80
alignmentInParent = scalafx.geometry.Pos.Center
}
JavaFX is reusing cells when rendering. This is especially noticeable when dynamically updating TableView content. Your cellFactory has to clear cell content when receiving and empty or null item: text and graphic need to be set to null. It may be sufficient to simply check for newChange == null
cellFactory = { _ =>
new TableCell[Quote, String] {
item.onChange { (_, _, newChange) =>
if (newChange == null) {
text = null
graphic = null
else {
if (newChange.toString.contains("+")) textFill = Color.Green
else textFill = Color.Red
text = newChange
}
}
}
}
It that is nor reliable you will have to implement the cellFactory the JavaFX way by implementing javafx.scene.control.TableCell and overwriting method updateItem that is passing in the empty flag:
cellFactory = {_ =>
new javafx.scene.control.TableCell[Quote, String] {
override def updateItem(item: String, empty: Boolean): Unit = {
super.updateItem(item, empty)
if (item == null || empty) {
text = null
graphic = null
}
else {
...
}
}
}
}
I have 2 realm object A and B linked with a relationship :
class A: Object {
let Bs = List<B>()
}
class B: Object {
dynamic var Id:Int = 0
}
So now, I need to get all A objects where the first Bs has the Id = 1.
If I use this line of code :
realm.objects(A).filter("ANY Bs.Id = 1")
I get all A objects, where one of the Bs has the Id = 1. But in my case, I need to check only the first Bs. Is it possible to do that in Realm ? Is there something like :
realm.objects(A).filter("FIRST Bs.Id = 1")
or
realm.objects(A).filter("TOP Bs.Id = 1")
Thank you for your help ! :)
Regards,
How about:
realm.objects(A).filter("ANY Bs.Id = 1").first
Do you have any other conditions?
I need help formatting my link query properly, I am using EF 3.5:
Dim mediators = (From m In entity.Mediators _
Where m.MediatorAvailabilities.Available = "Weekends"
Where (m.isActive = True) _
Order By m.Sequence _
Select New RankingCriteria() With { _
.FirstName = m.FirstName, _
.LastName = m.LastName, _
.CompanyName = m.CompanyName, _
.PhoneHome = m.PhoneHome, _
.PhoneWork = m.PhoneWork, _
.PhoneMobile = m.PhoneMobile, _
.Email = m.Email _
}).ToList()
I have a navigation property in Mediators to MediatorAvailabilities I want to do something like what is in where clause above in order to filter my results. It's not letting me navigate to the appropriate column by doing this: m.MediatorAvailabilities.Available.
How do I do this filter properly?
Thanks, Justin.
You will need to use the Any method. I dont know the proper VB syntax, but it should look something like this:
Where m.MediatorAvailabilities.Any(ma => ma.Available = "Weekends")