I have TWO tables. My primary table is called Student
, secondary table is Marks
. Dapper is new for me.
This is my code:
s_id
is the primary key in the Student
table and is foreign key in Marks
table (student (parent) – marks(child)).
Controller: join
public ActionResult Index()
{
string sql ="SELECT TOP 10 * FROM Student AS A INNER JOIN Mark AS B ON A.S_ID = B.S_ID";
using (SqlConnection connection = new SqlConnection(connectionstring))
{
var studentDictionary = new Dictionary<int,Student>();
var list = connection.Query<Student,Marks,Student>
(
sql,(student, marks) =>
{
Student Entry;
if (!studentDictionary.TryGetValue(student.S_ID,out Entry))
{
Entry = student;
Entry.Marks = new List<Marks>();
studentDictionary.Add(Entry.S_ID, Entry);
}
Entry.Marks.Add(marks);
return Entry;
},
splitOn:"S_ID")
.Distinct()
.ToList();
ViewBag.list = list;
}
return View();
}
Result.cs
join model
public class Result
{
public string S_Name { get; set; } //student.cs
public string S_LName { get; set; } //students.cs
public int Score { get; set; } //marks.cs
public string Status { get; set; } //marks.cs
}
How to access both student and marks tables columns using result.cs class? It's accessing only student columns why marks table columns not accessing view side?
How can I resolve this issue?
View:
@model IEnumerable<Dapper2Join.Models.Result>
@{
@foreach (var per in ViewBag.list)
{
<tr>
<td>@per.S_Name</td>
<td>@per.S_LName</td>
<td>@per.Score</td>
<td>@per.Status</td>
</tr>
}
By default, Dapper mappings work on conventions. You want your Result
class as output from query with only selected columns. There are two mistakes you are doing.
You are unnecessarily returning all the columns from both two tables. Instead, you can simply ask for columns you need. Change your SQL query something like below:
string sql ="SELECT TOP 10 Student.S_Name, ... Marks.Score, .... FROM Student INNER JOIN Mark ON Student.S_ID = Mark.S_ID";
Note that I do not know the column names in your table. You may need to use column aliases if those does not match with your property names. Refer the links at the bottom for more information.
You are mapping Student
and Marks
classes with result returned by Query
. Instead, you can directly map the class you want; i.e. Result
. Change your call to Query
something like below:
var list = connection.Query<Result>(sql, .....);
Apart from default behavior, Dapper also provides more flexibility and features in mapping. For more details about mapping with Dapper, refer these two answers.