-2

I'm working on a C# project that incorporates SQL, mainly using entities and linq.

Let's say I have two tables.

Table 1

primary key | name | date

Table 2

primary key | fktable1 | price

I would like to display Name, Date AND price in a datagrid. How can I pull the two - or one if we do it vice versa - values out of table 1 by only referencing the Foreign Key(Which is the Primary Key of Table 1) ?

Chopi
  • 1,123
  • 1
  • 12
  • 23
S. Hoppe
  • 1
  • 2
  • 2
    Do you mean you are using Entity Framework ? – Pac0 Apr 19 '18 at 11:45
  • 1
    I don't get what ur expected result is (**please add that to your question**). You could maybe `join` the tables and then only pass the `key` once .. ? – Felix D. Apr 19 '18 at 11:46
  • What does this have to do with c#? – Liam Apr 19 '18 at 11:47
  • Welcome to Stack Overflow. To get good answers, you will need to ask your questions a bit differently: 1. You are expected to do some research beforehand. That will very likely anser your question, since it seems to be very basic. You should provide some code and sample data to clarify your point. – Sefe Apr 19 '18 at 11:47
  • What do you want to do if there are multiple entries in table 2 for a given fktable1? Also what have you tried? Where are you having problems? etc. – Chris Apr 19 '18 at 11:48

3 Answers3

0

If your only problem is the sql statement you could use something like this (or "join"):

select t1.name, t1.date, t2.price from table1 t1, table2 t2 where t1.primary_key = t2.foreign_key;

If you have other problems please provide us some more details...

Gaterde
  • 779
  • 1
  • 7
  • 25
0

Supposing you have your data in IEnumerable<Table1> Table1List and IEnumerable<Table2> Table2List, you can use LINQ :

Table1List.Join(Table2List, 
    t1 => t1.PrimaryKey, // replace PrimaryKey by your actual field storing primary key
    t2 => t2.fkTable1,
    (t1, t2) => new { t1.Name, t1.Date, t2.Price } 
 )

This will correspond more or less to the SQL query :

SELECT t1.Name, t1.Date, t2.Price
FROM Table1 t1
INNER JOIN Table2 t2 ON t1.PrimaryKey = t2.fkTable1
Pac0
  • 21,465
  • 8
  • 65
  • 74
0

Yes you can select any column by joining the tow tables. example: SELECT Name, Date AND price FROM table 1 INNER JOIN table 2 ON table1.key=table2.fktable1

Sinte
  • 91
  • 1
  • 10