Last active
February 9, 2020 23:49
-
-
Save kironroy/43728385116e14a3a654d4d35721db9f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using DataAccessLibrary.Models; | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
namespace DataAccessLibrary | |
{ | |
// this class will use the SQLDataAccess.cs | |
public class SqlCRUD | |
// this class actually talks to the database | |
{ | |
private readonly string _connectionString; | |
private SqlDataAccess db = new SqlDataAccess(); | |
public SqlCRUD(string connectionString) | |
{ | |
_connectionString = connectionString; | |
} | |
public List<BasicContactModel> GetAllContacts() | |
{ | |
string sql = "select Id, FirstName, LastName from dbo.Contacts"; | |
// dynamic create a new anonymous object | |
return db.LoadData<BasicContactModel, dynamic>(sql, new { }, _connectionString); | |
} | |
public FullContactModel GetFullContactById(int id) | |
{ | |
// @Id is parameter in SQL, leaving out @ can lead to SQL injection | |
string sql = "select Id, FirstName, LastName, from dbo.Contacts where Id = @Id"; | |
FullContactModel output = new FullContactModel(); | |
output.BasicInfo = db.LoadData<BasicContactModel, dynamic>(sql, new { Id = id }, _connectionString) | |
.FirstOrDefault(); | |
if (output.BasicInfo == null) | |
{ | |
// do something to tell user the record wasn't found | |
// throw new Exception("User not found"); | |
return null; | |
} | |
sql = @"select e.*, ce.* from dbo.EmailAddresses e | |
inner join dbo.ContactEmail ce on ce.EmailAddressId = e.Id | |
where ce.ContactId = @Id"; | |
output.EmailAddress = db.LoadData<EmailAddressModel, dynamic>(sql, new { Id = id }, _connectionString); | |
sql = @"select p.* from dbo.PhoneNumbers p | |
inner join dbo.ContactPhoneNumbers cp on cp.PhoneNumberId = p.Id | |
where cp.ContactId = @Id"; | |
output.PhoneNumbers = db.LoadData<PhoneNumberModel, dynamic>(sql, new { Id = id }, _connectionString); | |
return output; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment