Sarra
Sarra

Reputation: 99

Get the last value of property in table using LINQ asp.net mvc

I want to get the value if a number is inserted into database. I've used the Last function but it didn't work and returned error:

last not defined by LINQ TO ENTITIES.

This is the code I've used :

int  NumD = LigneCommande.Last().NumDocument;

This is my class LigneCommande :

public partial class LigneCommande
{


    [Key]
    [Column(Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int NumDocument { get; set; }

    [Key]
    [Column(Order = 1)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int NumLigne { get; set; }

    [Required]
    [StringLength(20)]
    public string CodeArticle { get; set; }

    public int Quantite { get; set; }

    public int Disponible { get; set; }

    public decimal PrixUnitaire { get; set; }

    public byte Existe { get; set; }

    [Required]
    [StringLength(50)]
    public string Designation { get; set; }

    public byte Commander { get; set; }

    [Required]
    [StringLength(50)]
    public string Nature { get; set; }

    public DateTime DateDisponibilite { get; set; }

    [Required]
    [StringLength(50)]
    public string commentaire { get; set; }

    [Required]
    [StringLength(20)]
    public string numFacture { get; set; }

    public decimal? Remise { get; set; }

    public decimal? QteANNULEE { get; set; }

    public int? statusAnnulee { get; set; }

    [Column("Relicat Qte")]
    public decimal? Relicat_Qte { get; set; }
}

I tried to changed Last()with First() just for testing and it works fine. Can someone help me?

Upvotes: 0

Views: 454

Answers (3)

suulisin
suulisin

Reputation: 1434

int NumD = LigneCommande.AsEnumerable().LastOrDefault();

Upvotes: -1

David
David

Reputation: 218877

There really isn't a concept of "last" in an open-ended data source. For example, note that in SQL there is no syntax for taking the BOTTOM 1 record, just the TOP 1.

But "first" works just as well if you sort descending. Something like this:

int NumD = LigneCommande.OrderByDescending(l => l.SomeProperty).First().NumDocument;

That would give you the "last" object by ordering them in reverse order and taking the "first". All you need to do is define what that order is.

Upvotes: 3

Scott Selby
Scott Selby

Reputation: 9570

no one would be able to answer this unless we knew what LigneCommande was defined as. The only way that I could see this code working is id LigneCommande was some type of IEnumerable<int> or int[] which it is probably not since you said this is comming for the database. What you probably want is something like this:

   int  NumD = LigneCommande.Select(x => x.MyColumnNameThatIsAInt).LastOrDefault();

Upvotes: 1

Related Questions