I have these related classes, which are also tables in SQL: Board and BoardItemsNeeded I am wondering if using an Extension method is a reasonable way of optionally loading the child objects:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Dapper;
using Dapper.Contrib.Extensions;
[Table("board")]
public partial class Board
{
[Key]
public int id { get; set; }
public int CustomerCuid { get; set; }
public string ProjectName { get; set; }
public DateTime CreateDate { get; set; }
public short SalesEmployeeId { get; set; }
public DateTime? LastModifiedDate { get; set; }
public IEnumerable<BoardItemsNeeded> BoardItemsNeeded { get; set; }
public Board GetById(int id)
{
using (IDbConnection cn = new SqlConnection(g.Global.CONX))
{
cn.Open();
return cn.Get<Board>(id);
}
}
}
public static class ExtensionMethods
{
public static Board Deep(this Board value)
{
using (IDbConnection cn = new SqlConnection(g.Global.CONX))
{
cn.Open();
value.BoardItemsNeeded = cn.Query<BoardItemsNeeded>("SELECT * FROM board_items_needed WHERE BoardId = @id ", new { @id = value.id });
}
return value;
}
}
AND
[Table("board_items_needed")]
public partial class BoardItemsNeeded
{
[Key]
public int id { get; set; }
public int BoardId { get; set; }
public short ItemType { get; set; }
public decimal Size { get; set; }
public string Color { get; set; }
}
I can access the full object like this:
var board = new Board();
board = board.GetById(2).Deep();
I was messing around with interfaces, generics and repositories and came back to just doing things like this. I'm trying to develop a small pattern for various business classes in the db I'm working with. In lieu of the extension method, I suppose I could make another method under the Board class to do it. I'm just not sure if I'm approaching things right. I want to get it right before committing to a pattern.
Aucun commentaire:
Enregistrer un commentaire