简体   繁体   中英

How can I pass values from Entity to Presentation in c#

How can I pass the value from Entity Layer to Presentation Layer. I have populated the object Person but when I call it in Presentation it became null.

Can anyone help me. Thanks in advance!

Entity:

public class Person
{
    public int PersonID { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
}

DataLayer:

public List<Person> GetPersonSingleByPersonID(string personID)
{
    List<Person> objPerson = new List<Person>();
    DataTable dt = new DataTable();

    ...

    foreach (DataRow dr in dt.Rows)
    {
        objPerson.Add(new Person()
        {
            PersonID = dr["PersonID"].ToString(),
            Firstname = dr["Firstname"].ToString(),
            Lastname = dr["Lastname"].ToString()            
        });
    }
    return objPerson;
}

PresentationLayer:

Person objPerson = new Person(); //I think error goes here
txtPersonID.Text = objPerson.PersonID;
txtFirstname.Text = objPerson.Firstname;
txtLastname.Text = objPerson.Lastname;

There are a few issues with your code:

  1. Why GetPersonSingleByPersonID(string personID) returns a list? If you want to return a single person your method should be defined as Person GetPersonSingleByPersonID(string personID)

  2. You are not calling GetPersonSingleByPersonID(string personID) method at all. Instead you are creating a new 'blank' instance of Person class ( Person objPerson = new Person() ) You need to call GetPersonSingleByPersonID(id) and since you're returning a list instead of a single object (see point 1.) you probably want to add .FirstOrDefault() .

Person objPerson = GetPersonSingleByPersonID(id).FirstOrDefault()

you need to call the GetPersonaSingleByPersonId() method in your data access layer. create an instance of your DAL and then call the method. this will return the object you want with the details and then you finally assign it to the textboxes.

remember though, the method returns a collection... so you would be overwriting the previous values in your textbox if you are going through the entire collection and writing it to the textbox.

最好在数据表示之间有一个业务层,在该业务层中,您可以从数据层获取实体并进行处理,然后转换为表示层对象。

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