简体   繁体   中英

Trouble with postgres query in entity framework core

So I have a table as such:

[Table("Box", Schema = "dbo")]
    public partial class Box
    {
        [Column("eventId")]
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [StringLength(200)]
        public int EventId {get;set;}

        [Column("uuid")]
        public int Uuid {get;set;}

        [Column("localIndex")]
        public int LocalIndex {get;set;}

        [Column("rack")]
        public string Rack {get;set;}

        [Column("shelf")]
        public string Shelf{get;set;}

        [Column("fag")]
        public string Fag{get;set;}

        [Column("municipality")]
        public string Municipality {get;set;}

        [Column("organization")]
        public string Organization {get;set;}

        [Column("Entries")]
        public string Entries{get;set;}

    }

The database is event driven so the uuid for a particular box will remain constant however everything else may change, so what I want to get is the newest edition of all unique UUID boxes. Is there some succinct query I can run to accomplish this?

As right now as a temporary solution I just get all the boxes which match a specific where clause and run the result through this function:

let getLatest (list : Box list) = 
    list 
    |> List.filter(fun x -> list 
                            |> List.forall(fun y ->         
                                    not (y.uuid = x.uuid && y.eventId > x.eventId)))

Which needless to say is probably not the best way of doing it but it functions. However if anyone has any idea it would be most appreciated.

I would solve this problem by grouping your boxes by UUID , then ordering each group by eventId and taking first record from each group. In code it would look like:

let getLatest2 (list : Box list) = 
    list 
    |> List.groupBy (fun x-> x.uuid)
    |> List.map (fun (uuid, values) -> 
                    values 
                    |> List.sortByDescending (fun x->x.eventId) 
                    |> List.head)

To be honest, I'm not sure if it will be correctly translated with EF to SQL query or if it has any advantage over your original solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM