Skip to content

Instantly share code, notes, and snippets.

@kironroy
Last active February 9, 2020 23:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kironroy/43728385116e14a3a654d4d35721db9f to your computer and use it in GitHub Desktop.
Save kironroy/43728385116e14a3a654d4d35721db9f to your computer and use it in GitHub Desktop.
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