简体   繁体   中英

get last record of a table in database?

i am developing a project and after the user insert the data of the customer he suppose to print the ID and the name of the Customer, this is the code of the ID

int getPatnID()
    {
        int ID = (from i in Db.Patients
                  select i.patn_ID).Max();
        return ID;
    }

i have write the code to get the name but i cant finish it

string getPatnName()
    {
        string name = (from n in Db.Patients
                       select n.patn_name).

        return name;
    }

How should i write to complete it??

This should always get the last inserted record at time of execution (assuming patn_id is auto-incrementing)

string GetPatnName() 
{
    string name = (from n in Db.Patients 
                   orderby n.patn_ID descending 
                   select n.patn_name).FirstOrDefault();
    return name;
}
string getPatnName() {
    string name = Db.Patients.Last(p => p.patn_ID).patn_name;
    return name;
}

I suggest you spend some more time studying LINQ - it is a very rich and powerful library: http://msdn.microsoft.com/en-us/library/bb397926.aspx

Change getPatnName to take an id:

string getPatnName(int id)
{
    string name = (from n in Db.Patients
                   where n.patn_ID == id
                   select n.patn_name).SingleOrDefault();

    return name;
}

and give it the result of getPatnID()

If you are trying to get the name of the last patient you just entered, and you have the ID from the first query, you just need a where clause in your LINQ.

string name = (from n in Db.Patients
       where n.patn_ID == ID
       select n.patn_name);

Getting the id the way you do is wrong. Not sure what you're using, but both linq-2-sql and entity framework fill in the entity Id when saving changes:

    Patient patient = new Patient();
    Console.WriteLine(patient.Id); // will NOT be filled in
    Db.Patients.Add(patient);
    Db.SubmitChanges(); // SaveChanges in EF
    Console.WriteLine(patient.Id); // will be filled in

Why not just create a patient class an return an instance as shown below

public class Patient
{
    public int PatientID { get; set; }
    public string Name { get; set; }
}


static Patient getDetails()
    {
        using (DataClasses1DataContext db = new DataClasses1DataContext())
        {
            var c = (from x in db.Patients.OrderByDescending(u => u.PatientID)
                     select new Patient()
                     {
                         PatientID = x.PatientID,
                         Name = x.Name
                     }).FirstOrDefault();
            return c;
        }

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