简体   繁体   中英

Retrieve information from relational database

I'm developping an application with c# and ADO .NET entity data model, i have a table Articles(idArticle, nameArticle, statusArticle, idSubject), in relation with another table Subjects(idSubject,nameSubject). Subjects.idSubject = Articles.idSubject. Aftrer retrieving the first article that have statusArticle=0:

Articles firstArticle = db.Articles.FirstOrDefault(u => u.statusArticle == false);
    if (firstArticle != null)
    {
        textBox1.Text = firstArticle.nameArticle;
    } 

I want to show in another textBox the name of the subject of this article (nameSubject), how can i select the nameSubject of this article and show it in a textBox?

Not sure if I am getting you correctly but have you tired:

Articles firstArticle = db.Articles.FirstOrDefault(u => u.statusArticle == false);
if (firstArticle != null)
{
    textBox1.Text = firstArticle.nameArticle;
    textBox2.Text = firstArticle.Subject.nameSubject;
} 

Subject would have to be the name of the navigation property on your entity.. If you are in visual studio have a look at what properties are on firstArticle using intellisense, there should be a property that returns a Subject that would link to that item.

Are you using codefirst, DB first or model first approach to EF? Each of these has ways to check and configure what the navigation property would be called and whether it would exist - I am assuming DB first and what I remember of standard naming.

You can try this if the Articles class doesn't have an association/navigation property:

    Articles(idArticle, nameArticle, statusArticle, idSubject)
    Subjects(idSubject,nameSubject)

    Articles firstArticle = db.Articles.FirstOrDefault(u => u.statusArticle == false);
    if (firstArticle != null)
    {
        textBox1.Text = firstArticle.nameArticle;
        Subject subject = db.Subjects.FirstOrDefault(s => s.idSubject == firstArticle.idSubject);
        textBox2.Text = (subject != null) ? subject.nameSubject : string.Empty;
    } 

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